简体   繁体   中英

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

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.

首先,为按钮容器命名(例如,我将其命名为“ Grid1”),这是查找按钮的代码:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM