我有一个包含按钮和其他控件的UserControl:
<UserControl>
<StackPanel>
<Button x:Name="button" />
...
</StackPanel>
</UserControl>
当我创建该控件的新实例时,我想要获取Button的Command属性:
<my:GreatUserControl TheButton.Command="{Binding SomeCommandHere}">
</my:GreatUserControl>
当然,“TheButton.Command”的东西不起作用。
所以我的问题是:使用XAML,如何在用户控件中设置按钮的.Command属性?
答案 0 :(得分: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));
在你的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>
所以你的按钮绑定到UserControl本身的命令。现在您可以在父窗口中设置它:
<my:GreatUserControl SomeCommand="{Binding SomeCommandHere}" />