2014-03-07 83 views
0

比方說,我有兩個按鈕,如下定義:WPF從按鈕傳遞按鈕內容?

<Button Content="ButtonA" Command="{Binding [SomeTerminal].SomeCommand}"/> 
<Button Content="ButtonB" Command="{Binding [SomeTerminal].SomeCommand}"/> 

我想知道是否有可能搶按鈕的內容?含義當用戶點擊第一個按鈕時,我可以在我的SomeCommand方法中獲得ButtonA

+0

按鈕沒有名字,你想要的內容?命令的外觀是什麼? –

+0

@ErnodeWeerd:感謝您提醒誤導性信息 –

+0

您可以使用CommandParameters, –

回答

5

在「純」 MVVM解決方案,您將需要把視圖模型和數據綁定按鈕的內容,這個數據來顯示它。然後您可以通過Command參數將綁定數據傳遞給命令。從查看

<Button Content="{Binding SomeDataA}" 
     Command="{Binding [SomeTerminal].SomeCommand}" 
     CommandParameter="{Binding SomeDataA}" /> 
<Button Content="{Binding SomeDataB}" 
     Command="{Binding [SomeTerminal].SomeCommand}" 
     CommandParameter="{Binding SomeDataB}" /> 

獲取UI數據被認爲是不好的做法,因爲它會在視圖模型上查看的依賴使其更難檢測。

1

你可以使用一個CommandParameter:

<Button Content="ButtonA" Command="{Binding [SomeTerminal].SomeCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Content}" /> 
<Button Content="ButtonB" Command="{Binding [SomeTerminal].SomeCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Content}" /> 
1

您可以使用此,

<Button x:Name="BtnA" Content="ButtonA" Command="{Binding [SomeTerminal].SomeCommand}" CommandParameter="{Binding ElementName=BtnA, Path=Content}" /> 

<Button Content="ButtonA" Command="{Binding [SomeTerminal].SomeCommand}" CommandParameter="{Binding Path=Content, RelativeSource={RelativeSource Self}}" /> 
+0

ButtonA是內容,而不是名稱,它的問題也是錯誤的。 – Herm