【问题标题】:In WPF, how to get the name of a control by its tag in code behind?在 WPF 中,如何通过代码中的标签获取控件的名称?
【发布时间】:2016-04-12 10:06:57
【问题描述】:

我有一些带有Tag 属性的Buttons:

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

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

【问题讨论】:

  • 为什么?如果您可以访问 Tag 属性,则您已经拥有 Button。您可以添加一些您想要达到的目标的细节。
  • 您能解释一下您何时以及为什么要这样做吗?
  • @Clemens - 我没有按钮。我有一个生成数字的函数,我想根据该数字选择按钮。现在,Tag 属性用于保存自定义数据,所以我认为将这个数字放在那里是一个不错的选择。

标签: c# wpf xaml tags


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    使用 RelayCommand 遵循 MVVM 模式...

        <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

    【讨论】:

    • 又如何从后面的代码中获取呢?非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 2011-11-21
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    相关资源
    最近更新 更多