在WPF中,如何通过隐藏代码中的标签获取控件的名称?
In WPF, how to get the name of a control by its tag in code behind?
我有一些 Button
具有 Tag
属性:
<Button x:Name="Button1" Tag="1" />
<Button x:Name="Button2" Tag="2" />
<Button x:Name="Button3" Tag="3" />
<!-- etc. -->
我希望能够使用标签从代码隐藏中找到 Button
的名称。如何做到这一点?谢谢
使用 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
首先命名按钮的容器(比如我命名为"Grid1")
这是查找按钮的代码:
var foundButton = Grid1.Children.OfType<Button>().Where(x => x.Tag.ToString() == "2").FirstOrDefault();
我有一些 Button
具有 Tag
属性:
<Button x:Name="Button1" Tag="1" />
<Button x:Name="Button2" Tag="2" />
<Button x:Name="Button3" Tag="3" />
<!-- etc. -->
我希望能够使用标签从代码隐藏中找到 Button
的名称。如何做到这一点?谢谢
使用 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首先命名按钮的容器(比如我命名为"Grid1") 这是查找按钮的代码:
var foundButton = Grid1.Children.OfType<Button>().Where(x => x.Tag.ToString() == "2").FirstOrDefault();