預設只有繼承 ButtonBase(Button、CheckBox、RadioButton 等)的控制項直接支援 Command 屬性。若要讓 Label、TextBlock、ListBoxItem 等任意元素繫結命令,需引入 Microsoft.Xaml.Behaviors(原 System.Windows.Interactivity)。
Install-Package Microsoft.Xaml.Behaviors.Wpf(.NET Core/.NET 5+)System.Windows.Interactivity.dll。<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>
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:附加屬性集合,可掛載多個觸發器。System.Windows.Interactivity 需確保目標框架相容。EventTrigger 會訂閱事件,元素卸載時自動解除。