Reputation: 4435
I have some Button
s 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
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
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