代码之家  ›  专栏  ›  技术社区  ›  sudarsanyes

在wpf中以编程方式添加宿主控件时,命令绑定不起作用

  •  3
  • sudarsanyes  · 技术社区  · 14 年前

    这很奇怪。我有一个 用户控件(MyControl) 里面有个按钮。我添加了一个 此按钮的命令目标是再次添加到同一窗口的另一个用户控件。

    可能是什么原因。我是不是丢了什么东西?!?

    更新:

    *把我的话更好地表现为一种形象。我也上传了我的源代码和二进制文件@ https://code.google.com/p/commandbindingsample/

    http://cid-6fc1e241d4534589.office.live.com/embedicon.aspx/Wpf%20Samples/CommandBinding.zip

    alt text

    1 回复  |  直到 14 年前
        1
  •  1
  •   Robert Rossney    14 年前

    在用户控件中,您正在设置 CommandBinding 这样地:

    CommandTarget="{Binding ElementName=userControl11}"
    

    如果在程序运行时查看输出窗口,您将看到:

    System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=userControl11'. BindingExpression:(no path); DataItem=null; target element is 'Button' (Name=''); target property is 'CommandTarget' (type 'IInputElement')
    

    userControl11 在当前的命名空间中。见 this

    如果希望能够通过绑定在用户控件上设置命令目标,则需要将其公开为依赖项属性。您可以向控件添加这样的声明:

    public IInputElement CommandTarget
    {
        get { return (IInputElement)GetValue(CommandTargetProperty); }
        set { SetValue(CommandTargetProperty, value); }
    }
    
    public static readonly DependencyProperty CommandTargetProperty =
            DependencyProperty.Register("CommandTarget", typeof(IInputElement), typeof(UserControl1), new UIPropertyMetadata(null));
    

    在用户控件的XAML中,绑定到此属性:

    <Button Content="Click" 
            Command="local:Commands.ClickCommand" 
            CommandTarget="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=CommandTarget}" />
    

    我不能在你的项目中实现这一点,但那是因为我无法理解你的项目。您似乎有两个或三个名为 UserControl1

    我希望这对你有帮助。

    推荐文章