Reputation: 5550
Let's say I have two button defined as below:
<Button Content="ButtonA" Command="{Binding [SomeTerminal].SomeCommand}"/>
<Button Content="ButtonB" Command="{Binding [SomeTerminal].SomeCommand}"/>
May I know if it's possible to grab the content of the button? Meaning when user click the first button, I can get ButtonA
in my SomeCommand
method?
Upvotes: 3
Views: 4391
Reputation: 2665
You can use this,
<Button x:Name="BtnA" Content="ButtonA" Command="{Binding [SomeTerminal].SomeCommand}" CommandParameter="{Binding ElementName=BtnA, Path=Content}" />
or
<Button Content="ButtonA" Command="{Binding [SomeTerminal].SomeCommand}" CommandParameter="{Binding Path=Content, RelativeSource={RelativeSource Self}}" />
Upvotes: 1
Reputation: 2989
you can use a 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}" />
Upvotes: 5
Reputation: 50672
In a 'pure' MVVM solution you would need to put data in the ViewModel and bind the contents of the buttons to this data to display it. You could then also pass the bound data to the command through a Command parameter.
<Button Content="{Binding SomeDataA}"
Command="{Binding [SomeTerminal].SomeCommand}"
CommandParameter="{Binding SomeDataA}" />
<Button Content="{Binding SomeDataB}"
Command="{Binding [SomeTerminal].SomeCommand}"
CommandParameter="{Binding SomeDataB}" />
Getting UI data from a View is considered bad practice because it creates a dependency in the ViewModel on the View making it harder to test.
Upvotes: 6