聊一下Button事件、命令、行为的触发顺序

1、我们新建一个xaml

<StackPanel Width="200" Margin="20">
    <Button Height="30" Content="按钮" Command="{Binding MsgCommand}" x:Name="btn" Margin="10"/>
</StackPanel>

2、分别在后台写入命令和事件

  public ICommand MsgCommand { get; set; }
 MsgCommand = new DelegateCommand(ExecuteCommand);
    private void ExecuteCommand()
   {
       MessageBox.Show("触发命令");
   }
     btn.Click += Btn_Click;
    private void Btn_Click(object sender, RoutedEventArgs e)
   {
     MessageBox.Show("触发事件");
   }

3、运行,发现事件先触发,

由于事件处理程序是直接附加到按钮的 Click 事件上的,所以在点击按钮时会先触发 Btn_Click 事件处理程序,然后才会执行与按钮 Command 属性相关联的命令 MsgCommand

4、我们接着添加行为

 public class ButtonBehavior:Behavior<FrameworkElement>
 {
     public string SelectItem
     {
         get { return (string)GetValue(SelectItemProperty); }
         set { SetValue(SelectItemProperty, value); }
     }
     public static readonly DependencyProperty SelectItemProperty =
         DependencyProperty.Register("SelectItem", typeof(string), typeof(ButtonBehavior), new PropertyMetadata(null,OnSelectedChanged));

     private static void OnSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
     {
         MessageBox.Show("回调");
     }

     protected override void OnAttached()
     {
         MessageBox.Show("OnAttached");
     }

     protected override void OnChanged()
     {
         MessageBox.Show("OnChanged");
     }

     protected override void OnDetaching()
     {
         MessageBox.Show("OnDetaching");
     }
 }

5、修改前台代码和后台代码

 <StackPanel Width="200" Margin="20">
     <i:Interaction.Behaviors>
         <local:ButtonBehavior SelectItem="{Binding SelectedValue,Mode=TwoWay}"/>
     </i:Interaction.Behaviors>
     <Button Height="30" Content="按钮1" Command="{Binding MsgCommand}" x:Name="btn" Margin="10"/>
 </StackPanel>
  public class MainWindowViewModel : BindableBase
 {
     private string _selectedValue;

     public string SelectedValue
     {
         get { return _selectedValue; }
         set { SetProperty<string>(ref _selectedValue, value); }
     }

     public MainWindowViewModel()
     {
         MsgCommand = new DelegateCommand(ExecuteCommand);
     }

     private void ExecuteCommand()
     {
         SelectedValue = "123";
         MessageBox.Show("触发命令");
     }

     public ICommand MsgCommand { get; set; }
 }

运行后

触发顺序为

1、界面初始化之前,Freezable的Changed事件,2、Behavior的OnAttached事件,

点击按钮后,依次触发,按钮事件、字符串改变,回调,Changed事件,按钮命令,