我有一个包含按钮和其他一些控件的 UserControl:
<UserControl>
<StackPanel>
<Button x:Name="button" />
...
</StackPanel>
</UserControl>
当我创建该控件的新实例时,我想获取按钮的 Command 属性:
<my:GreatUserControl TheButton.Command="{Binding SomeCommandHere}">
</my:GreatUserControl>
当然,“TheButton.Command”的东西不起作用。
所以我的问题是:使用 XAML,如何设置用户控件内按钮的 .Command 属性?
将依赖属性添加到 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}" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)