且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在用作另一个用户控件中的按钮的用户控件中创建按钮的命令属性

更新时间:2023-12-06 11:33:22

Step : 1 - Create new command as a DepenedecyProperty and implement it 

Steo : 2 -  Bind Command property in the button the the MyButtonCommandProperty in your UserControl.


public Class YourUserControl: UserControl 
 {

      public YourUserControl()
      {
          MyButtonCommad = new RelayCommand
                     (
                         () => { // do some stuff in execute delegate},
                         () => { return true ;}                                                        
                     );
      }

      public bool MyButtonCommad 
      {
           get { return (ICommand)GetValue(MyButtonCommandProperty ); }
           set { SetValue(MyButtonCommandProperty , value); }
      }    

      public static readonly DependencyProperty MyButtonCommandProperty = 
                             DependencyProperty.Register("MyButtonCommad ", typeof(ICommand),new FrameworkPropertyMetadata(null));

 }


// XAML : 

<Window>
      <StackPanel>
          <Button Command={Binding ElementName=control1,Path=MyButtonCommad ,Mode=OneWay/>
          <YourUserControl: x:Name="control1" />
      </StackPanel>
 </Window>