在用户控件中,您正在设置
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
我希望这对你有帮助。