我有Button
个Tag
属性:
<Button x:Name="Button1" Tag="1" />
<Button x:Name="Button2" Tag="2" />
<Button x:Name="Button3" Tag="3" />
<!-- etc. -->
我希望能够使用标记从代码隐藏中找到Button
的名称。怎么做到这一点?感谢。
答案 0 :(得分:3)
首先命名按钮容器(例如我将其命名为&#34; Grid1&#34;) 以下是找到按钮的代码:
var foundButton = Grid1.Children.OfType<Button>().Where(x => x.Tag.ToString() == "2").FirstOrDefault();
答案 1 :(得分:0)
使用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>
你应该通过标签&#39;值作为CommandParameter返回ViewModel