C# 在WPF中,如何通过代码隐藏中的标记获取控件的名称?

C# 在WPF中,如何通过代码隐藏中的标记获取控件的名称?,c#,wpf,xaml,tags,C#,Wpf,Xaml,Tags,我有一些带有标记属性的按钮: <Button x:Name="Button1" Tag="1" /> <Button x:Name="Button2" Tag="2" /> <Button x:Name="Button3" Tag="3" /> <!-- etc. --> 我希望能够使用标签从代码隐藏中找到按钮的名称。如何做到这一点?谢谢。按照MVVM模式使用RelayCommand <StackPanel>

我有一些带有标记属性的按钮:

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

我希望能够使用标签从代码隐藏中找到按钮的名称。如何做到这一点?谢谢。

按照MVVM模式使用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>

您应该按照MVVM模式使用RelayCommand将“Tag”值作为CommandParameter传递回ViewModel

    <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>

您应该将“Tag”值作为CommandParameter传递回ViewModel,首先命名按钮容器,例如我将其命名为Grid1 以下是查找按钮的代码:

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

首先命名按钮容器,例如我将其命名为Grid1 以下是查找按钮的代码:

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

为什么?如果可以访问“标记”属性,则已具有该按钮。你可以添加一些你想要达到的目标的细节。你能解释一下你什么时候以及为什么要这样做吗?@Clemens-我没有按钮。我有一个生成数字的函数,我想根据这个数字选择按钮。现在,Tag属性是用来保存自定义数据的,所以我认为把这个数字放在那里是个不错的选择。原因是什么?如果可以访问“标记”属性,则已具有该按钮。你可以添加一些你想要达到的目标的细节。你能解释一下你什么时候以及为什么要这样做吗?@Clemens-我没有按钮。我有一个生成数字的函数,我想根据这个数字选择按钮。现在,Tag属性是用来保存自定义数据的,所以我认为把这个数字放在那里是一个很好的选择?非常感谢。那么如何从代码背后获取它呢?谢谢。