【问题标题】:How: Bind to a UserControl's DependencyProperty, when the UserControl has a DataContext?如何:当 UserControl 具有 DataContext 时,绑定到 UserControl 的 DependencyProperty?
【发布时间】:2011-06-29 03:27:41
【问题描述】:

我的问题不是在UserControl 中连接DependencyProperties。这不是问题。当我将UserControl 中的按钮绑定到UserControlDependencyProperty 称为TargetCommand 时,当我在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 绑定方法都会正确连接。设置 DataContext 后两者都不起作用。

有没有办法在 MyUserControl 上设置 DataContext,并且仍然保留与 TargetCommand 的 DependencyProperty 绑定?

【问题讨论】:

    标签: c# wpf xaml datacontext dependency-properties


    【解决方案1】:

    您的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}" />
    

    【讨论】:

    • 很好...我忽略了这一点。谢谢
    【解决方案2】:

    不确定我是否在这里遗漏了一些东西,但是为什么在设置 DataContext 时需要在此处使用 DependencyProperty?为什么不在你的模型中有一个可以直接从按钮绑定的属性?

    【讨论】:

    • 把这个命令附加到我的模型上是没有意义的。从我的模型的角度来看。
    猜你喜欢
    • 2015-02-16
    • 2016-04-21
    • 2012-06-06
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    相关资源
    最近更新 更多