WPF UserControls - 在 UserControl 内的按钮上设置 .Command 属性按钮、属性、UserControls、WPF

2023-09-07 15:47:36 作者:无情便是王

我有一个包含按钮和其他一些控件的 UserControl:

I've got a UserControl that contains a button and some other controls:

<UserControl>
  <StackPanel>
     <Button x:Name="button" />
     ...
  </StackPanel>
</UserControl>

当我创建该控件的新实例时,我想获取 Button 的 Command 属性:

When I create a new instance of that control, I want to get at the Button's Command property:

<my:GreatUserControl TheButton.Command="{Binding SomeCommandHere}">
</my:GreatUserControl>

当然,TheButton.Command"这个东西是行不通的.

Of course, the "TheButton.Command" thing doesn't work.

所以我的问题是:使用 XAML,如何在我的用户控件中设置按钮的 .Command 属性?

So my question is: Using XAML, how can I set the .Command property of the button inside my user control?

推荐答案

将依赖属性添加到您的 UserControl 并将按钮的 Command 属性绑定到该属性.

Add a dependency property to your UserControl and bind the button's Command property to that.

所以在你的 GreatUserControl 中:

So in your 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 中:

And in your GreatUserControl's 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 本身的命令.现在您可以在父窗口中进行设置:

So your button binds to the command on the UserControl itself. Now you can set that in your parent window:

<my:GreatUserControl SomeCommand="{Binding SomeCommandHere}" />