簡體   English   中英

在WPF中,如何通過后面的代碼中的標簽獲取控件的名稱?

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

我有一些帶有Tag屬性的Button

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

我希望能夠使用標簽從代碼背后找到Button的名稱。 如何做到這一點? 謝謝。

首先,為按鈕容器命名(例如,我將其命名為“ Grid1”),這是查找按鈕的代碼:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM