3

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

当我在 xaml 中将 UserControl 静态添加到 CustomControl 的主机空间时,CommandBinding 系统工作正常,而如果以编程方式添加 UserControl(在此窗口的 Loaded 事件上),则同样不起作用。

可能是什么原因。我在这里错过了什么吗?!?

更新:

*将我的话更好地表示为图像。我还上传了带有二进制文件的源代码@ https://code.google.com/p/commandbindingsample/

http://cid-6fc1e241d4534589.office.live.com/embedicon.aspx/Wpf%20Samples/CommandBinding.zip(无版本)*

替代文字

4

1 回答 1

1

In your user control, you're setting the CommandBinding like this:

CommandTarget="{Binding ElementName=userControl11}"

If you look in the Output window while your program's running, you'll see this:

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')

This is because there's no element named userControl11 in the current namescope. See this for full details on how XAML namescopes work, but in short, XAML names are only visible within the page, window, or user control that they're declared in. You can't reference a name declared in your window from inside a user control.

If you want to be able to set a command target on a user control via binding, it needs to be exposed as a dependency property. You'd add a declaration like this to the control:

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));

and in the user control's XAML, bind to this property:

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

I can't actually get this to work in your project, but that's because I can't figure your project out. You seem to have two or three user controls named UserControl1 in different namespaces, and the names of the files in the project don't correspond to their contents, and there's not very much in the way of useful commentary. (Just in general, instead of saying "this doesn't work," describe the behavior you're expecting; that makes it a lot clearer to someone trying to help you what your actual problem might be.)

I hope this is helpful anyway.

于 2010-11-02T18:07:34.450 回答