我的问题不是在
在MainWindow中设置MyUserControl的DataContext后,MyUserControl中的绑定方法RelativeSource和ElementName都无法正常工作。是否有一种方法可以在MyUserControl上设置DataContext,并仍然保留到TargetCommand的DependencyProperty绑定?
UserControl
中连接DependencyProperties
。这不是问题。当我将UserControl
中的按钮绑定到UserControl
的名为TargetCommand
的DependencyProperty
时,当我在UserControl
上设置DataContext
时,绑定会中断。我尝试使用FindAncestor
和当然使用ElementName
,但只有在UserControl
没有DataContext
时才能使用它们。
有什么解决方法吗?
例子:
主窗口
<Window xmlns:UserControls="clr-namespace:SomeNameSpace">
<Grid>
<UserControls:MyUserControl
TargetCommand="{Binding PathToCommand}"
DataContext="{Binding PathToSomeModel}" />
MyUserControl 代码后台
public partial class MyUserControl : UserControl
{
public static readonly DependencyProperty TargetCommandProperty =
DependencyProperty.Register( "TargetCommand", typeof( ICommand ), typeof( MyUserControl ) );
public ICommand TargetCommand
{
get { return (ICommand)GetValue( TargetCommandProperty ); }
set { SetValue( TargetCommandProperty, value ); }
}
MyUserControl - Xaml
<UserControl x:Name="root">
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=TargetCommand}" />
<Button Command="{Binding Path=TargetCommand, ElementName=root}" />
在MainWindow中设置MyUserControl的DataContext后,MyUserControl中的绑定方法RelativeSource和ElementName都无法正常工作。是否有一种方法可以在MyUserControl上设置DataContext,并仍然保留到TargetCommand的DependencyProperty绑定?