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

后端 未结 1 543
我寻月下人不归
我寻月下人不归 2021-02-14 14:42

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


  
     
1条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-14 14:59

    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:

    
        
    
    

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

    
    

    0 讨论(0)
提交回复
热议问题