WPF UserControls - setting the .Command property on button inside UserControl

妖精的绣舞 提交于 2019-12-21 04:01:06

问题


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

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

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>

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

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


回答1:


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

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));

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>

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}" />


来源:https://stackoverflow.com/questions/2777452/wpf-usercontrols-setting-the-command-property-on-button-inside-usercontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!