首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WPF Command 繫結進階:讓任意控制項支援命令綁定

     編輯:關於.NET

預設只有繼承 ButtonBase(Button、CheckBox、RadioButton 等)的控制項直接支援 Command 屬性。若要讓 Label、TextBlock、ListBoxItem 等任意元素繫結命令,需引入 Microsoft.Xaml.Behaviors(原 System.Windows.Interactivity)。

安裝與引用

  • NuGet:Install-Package Microsoft.Xaml.Behaviors.Wpf(.NET Core/.NET 5+)
  • 或安裝 Expression Blend SDK 參考 System.Windows.Interactivity.dll。

XAML 實作

<Window ...
        xmlns:i="https://schemas.microsoft.com/xaml/behaviors"
        xmlns:vm="clr-namespace:MyApp.ViewModels">
    <Window.DataContext>
        <vm:MainViewModel/>
    </Window.DataContext>
    <Grid>
        <Button Content="標準按鈕" Command="{Binding NormalCommand}"/>
        
        <Label Content="雙擊觸發命令" Margin="0,40,0,0">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseDoubleClick">
                    <i:InvokeCommandAction Command="{Binding LabelDblClickCommand}" 
                                          CommandParameter="來自 Label"/>
                </i:EventTrigger>
                <i:EventTrigger EventName="MouseEnter">
                    <i:InvokeCommandAction Command="{Binding HoverCommand}"
                                          CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=Label}}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Label>
    </Grid>
</Window>

ViewModel

public class MainViewModel : INotifyPropertyChanged
{
    public ICommand NormalCommand => new RelayCommand(() => MessageBox.Show("Button Click"));
    public ICommand LabelDblClickCommand => new RelayCommand(msg => MessageBox.Show($"Label: {msg}"));
    public ICommand HoverCommand => new RelayCommand

關鍵類別

  • EventTrigger:指定來源事件(EventName)。
  • InvokeCommandAction:將事件轉發為命令,支援 CommandParameter。
  • Interaction.Triggers:附加屬性集合,可掛載多個觸發器。

優勢

  • **零 Code-behind**:邏輯完全在 ViewModel,符合 MVVM。
  • **任意事件對應命令**:Click、MouseEnter、KeyDown、Loaded 等皆可。
  • **參數靈活傳遞**:常值、繫結、RelativeSource、EventArgs 皆可。

注意事項

  • 舊專案用 System.Windows.Interactivity 需確保目標框架相容。
  • 大量使用時注意記憶體,EventTrigger 會訂閱事件,元素卸載時自動解除。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved