聊一下Button事件、命令、行為的觸發順序

孤沉發表於2024-03-26

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事件,按鈕命令,

相關文章