Dav*_*vid 6 wpf binding user-controls command dependency-properties
我正在尝试将命令传递给WPF用户控件中的元素.
<UserControl x:Class="MyApp.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- shortened -->
<Button Command="{Binding Command}">
<Button.Content>
<!-- shortened -->
</Button.Content>
</Button>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
public partial class MyControl : UserControl
{
public static readonly DependencyProperty CommandProperty
= DependencyProperty.Register("Command",
typeof(ICommand), typeof(MyControl));
//shortened
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
//shortened
}
Run Code Online (Sandbox Code Playgroud)
<uc:MyControl Command="{Binding DoStuffCommand}" /> <!-- shortened -->
Run Code Online (Sandbox Code Playgroud)
单击用户控件中的按钮时,没有任何反应.
当我调试时,该Command属性为null.
将命令绑定到用户控件外部的按钮确实有效.
这里出了什么问题?
默认DataContext为你的Button就是你的用户控件的DataContext,不是你的用户控件,所以你试图绑定到DataContext.Command的,而不是UserControl.Command
要绑定UserControl.Command,请使用RelativeSource绑定
<Button Command="{Binding Command, RelativeSource={
RelativeSource AncestorType={x:Type local:MyControl}}}">
Run Code Online (Sandbox Code Playgroud)
编辑刚刚注意到HB的答案,这也有用.通常我更喜欢RelativeSource绑定到ElementName1,因为有时我重命名项目并且过去常常忘记其他控件通过Name引用该项目
命名控件并使用ElementName:
<UserControl ...
Name="control">
<Button Command="{Binding Command, ElementName=control}">
<!-- ... -->
Run Code Online (Sandbox Code Playgroud)