如何在UserControl具有DataContext时绑定到其DependencyProperty?

3
我的问题不是在UserControl中连接DependencyProperties。这不是问题。当我将UserControl中的按钮绑定到UserControl的名为TargetCommandDependencyProperty时,当我在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绑定?
2个回答

3

你的PathToCommand定义在哪里?如果我正确理解你的例子,它应该在VisualTree中比UserControl更高的位置。在这种情况下,你需要绑定到具有包含PathToCommand的DataContext的任何控件,并绑定到DataContext.PathToCommand

<Window xmlns:UserControls="clr-namespace:SomeNameSpace">
    <Grid x:Name="PART_Root">
         <UserControls:MyUserControl 
             TargetCommand="{Binding ElementName=PART_Root, Path=DataContext.PathToCommand}" />

不错,我忽略了那个。谢谢。 - Nicholas

0

我不确定是否有什么地方漏掉了,但是为什么你在设置DataContext时需要DependencyProperty呢?为什么不在你的模型中拥有一个可以直接从按钮绑定的属性呢?


从我的模型的角度来看,将这个命令附加到它上面就没有意义。 - Nicholas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接