SuicideSheep
SuicideSheep

Reputation: 5550

WPF passing button content from button?

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

Answers (3)

Sankarann
Sankarann

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

Herm
Herm

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

Emond
Emond

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

Related Questions