2017-07-15 179 views

回答

1

如果您真的使用MVVM,則將每個按鈕的Command綁定到您的視圖模型中對應的ICommand。這將是兩個不同的命令,因此您不需要執行任何特殊操作就可以將一個按鈕與另一個按鈕區分開來。

XAML:

<Button Content="FirstButton" 
     Command="{Binding Path=FirstCommand, Mode=OneTime}"/> 
<Button Content="SecondButton" 
     Command="{Binding Path=SecondCommand, Mode=OneTime}"/> 

視圖模型:

public sealed class ViewModel : INotifyPropertyChanged 
{ 
    // ... 
    public ICommand FirstCommand { get; } 
    public ICommand SecondCommand { get; } 
    // ... 
} 
0

如果你想使用相同的Command多個按鈕,你可以使用CommandParameter

<Button Content="buttonContent1" Command="{Binding ButtonClickCommand}"      
         CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}"/> 

而在你的命令委託方法可以使用這樣的事情:

private void ButtonClickCommandHandler(object parameter) 
{ 
    switch(parameter.ToString()) 
    { 
     case buttonContent1: 
     ... 
     case buttonContent2: 
     ... 
    } 

}

這裏按鈕被按課程的內容確定您可以將其更改爲某個其他財產一樣Tag

+0

'Content'和'Tag'屬性對於'CommandParameter'來說是一個非常糟糕的選擇。創建一個枚舉,其中每個字段將標識一個按鈕並將這些字段作爲「CommandParameter」傳遞將會好得多。 – Maxim