Jud*_*ngo 10 data-binding wpf user-controls command
我有一个UserControl包含一个按钮和一些其他控件:
<UserControl>
<StackPanel>
<Button x:Name="button" />
...
</StackPanel>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
当我创建该控件的新实例时,我想要获取Button的Command属性:
<my:GreatUserControl TheButton.Command="{Binding SomeCommandHere}">
</my:GreatUserControl>
Run Code Online (Sandbox Code Playgroud)
当然,"TheButton.Command"的东西不起作用.
所以我的问题是:使用XAML,如何在用户控件中设置按钮的.Command属性?
Mat*_*ton 20
将依赖项属性添加到UserControl并将按钮的Command属性绑定到该属性.
所以在你的GreatUserControl中:
public ICommand SomeCommand
{
get { return (ICommand)GetValue(SomeCommandProperty); }
set { SetValue(SomeCommandProperty, value); }
}
public static readonly DependencyProperty SomeCommandProperty =
DependencyProperty.Register("SomeCommand", typeof(ICommand), typeof(GreatUserControl), new UIPropertyMetadata(null));
Run Code Online (Sandbox Code Playgroud)
在你的GreatUserControl的XAML中:
<UserControl
x:Class="Whatever.GreatUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="me"
>
<Button Command="{Binding SomeCommand,ElementName=me}">Click Me!</Button>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
所以你的按钮绑定到UserControl本身的命令.现在您可以在父窗口中设置它:
<my:GreatUserControl SomeCommand="{Binding SomeCommandHere}" />
Run Code Online (Sandbox Code Playgroud)