Michael Haddad
Michael Haddad

Reputation: 4435

In WPF, how to get the name of a control by its tag in code behind?

I have some Buttons with a Tag attribute:

<Button x:Name="Button1" Tag="1" />
<Button x:Name="Button2" Tag="2" />
<Button x:Name="Button3" Tag="3" />
<!-- etc. -->

I want to be able to find the name of the Button from code-behind, using the tag. How to accomplish that? Thanks.

Upvotes: 1

Views: 4469

Answers (2)

Afshin Aghazadeh
Afshin Aghazadeh

Reputation: 547

First of all name the container of buttons (For example I named it "Grid1") Here is the code to find your button:

var foundButton = Grid1.Children.OfType<Button>().Where(x => x.Tag.ToString() == "2").FirstOrDefault();

Upvotes: 5

User9995555
User9995555

Reputation: 1556

Following the MVVM patter using RelayCommand...

    <StackPanel>
        <Button Content="Button1" x:Name="Button1" Tag="1" Command="{Binding ButtonPressCommand}" CommandParameter="{Binding Path=Tag, RelativeSource={RelativeSource Self}}" />
        <Button Content="Button2" x:Name="Button2" Tag="2" Command="{Binding ButtonPressCommand}" CommandParameter="{Binding Path=Tag, RelativeSource={RelativeSource Self}}" />
        <Button Content="Button3" x:Name="Button3" Tag="3" Command="{Binding ButtonPressCommand}" CommandParameter="{Binding Path=Tag, RelativeSource={RelativeSource Self}}" />
    </StackPanel>

You should be passing the 'Tag' value back to the ViewModel as a CommandParameter

Upvotes: 1

Related Questions