Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF passing button content from button?

Tags:

c#

button

wpf

xaml

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?

like image 366
SuicideSheep Avatar asked Dec 28 '25 17:12

SuicideSheep


2 Answers

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.

like image 77
Emond Avatar answered Dec 31 '25 09:12

Emond


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}" />
like image 40
Herm Avatar answered Dec 31 '25 07:12

Herm