You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WPF按钮的点击事件处理器中访问内部文本控件?

如何在点击按钮时获取并显示内部化学元素信息

下面提供三种可行的解决方案,你可以根据实际场景选择:

方法1:给TextBlock命名(最直接简便)

直接给XAML里的每个TextBlock添加x:Name属性,这样就能在后台代码中直接访问它们的文本内容。

修改后的XAML代码片段:

<Button Grid.Row="5" Grid.Column="2"
        Background="#FF9935"
        BorderBrush="#FF9935"
        Margin="0,0,0,5"
        Click="Button_Click">
    <Button.Resources>
        <Style TargetType="Border">
            <Setter Property="CornerRadius" Value="5"></Setter>
        </Style>
    </Button.Resources>
    <Grid Height="66" Width="67">
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <!-- 给每个TextBlock添加x:Name -->
        <TextBlock x:Name="AtomicNumberTb" VerticalAlignment="Top" Grid.Row="0" FontSize="9">38</TextBlock>
        <TextBlock x:Name="SymbolTb" VerticalAlignment="Center" Grid.Row="1" FontSize="20" FontWeight="Bold">Sr</TextBlock>
        <TextBlock x:Name="ElementNameTb" Grid.Row="2" FontSize="10" FontWeight="DemiBold">Strontium</TextBlock>
        <TextBlock x:Name="AtomicWeightTb" Grid.Row="3" FontSize="8">87.62</TextBlock>
    </Grid>
</Button>

对应的C#事件处理器:

private void Button_Click(object sender, RoutedEventArgs e)
{
    string elementInfo = $"原子序数:{AtomicNumberTb.Text}\n" +
                         $"元素符号:{SymbolTb.Text}\n" +
                         $"元素名称:{ElementNameTb.Text}\n" +
                         $"原子量:{AtomicWeightTb.Text}";
    MessageBox.Show(elementInfo);
}

方法2:遍历可视化树获取控件(无需修改XAML命名)

如果不想给TextBlock加名称,可以通过遍历按钮的可视化树,找到内部的Grid和TextBlock控件。

C#事件处理器代码:

private void Button_Click(object sender, RoutedEventArgs e)
{
    // 转换sender为Button对象
    Button targetBtn = sender as Button;
    if (targetBtn == null) return;

    // 获取按钮内部的Grid容器
    Grid elementGrid = targetBtn.Content as Grid;
    if (elementGrid == null) return;

    // 收集Grid内的所有TextBlock
    List<TextBlock> textBlocks = new List<TextBlock>();
    foreach (var child in elementGrid.Children)
    {
        if (child is TextBlock tb)
        {
            textBlocks.Add(tb);
        }
    }

    // 按行顺序拼接信息(确保TextBlock顺序与XAML中一致)
    if (textBlocks.Count >= 4)
    {
        string elementInfo = $"原子序数:{textBlocks[0].Text}\n" +
                             $"元素符号:{textBlocks[1].Text}\n" +
                             $"元素名称:{textBlocks[2].Text}\n" +
                             $"原子量:{textBlocks[3].Text}";
        MessageBox.Show(elementInfo);
    }
}

方法3:数据绑定(推荐的WPF设计方式)

这种方式将元素数据与UI分离,更符合WPF的MVVM设计思想,也便于后续维护和扩展。

步骤1:定义元素数据类

public class ChemicalElement
{
    public int AtomicNumber { get; set; }
    public string Symbol { get; set; }
    public string Name { get; set; }
    public double AtomicWeight { get; set; }
}

步骤2:在窗口类中初始化数据

public partial class MainWindow : Window
{
    // 定义元素数据实例
    public ChemicalElement CurrentElement { get; set; } = new ChemicalElement
    {
        AtomicNumber = 38,
        Symbol = "Sr",
        Name = "Strontium",
        AtomicWeight = 87.62
    };

    public MainWindow()
    {
        InitializeComponent();
        // 设置窗口DataContext,让UI能绑定到数据
        DataContext = this;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Button targetBtn = sender as Button;
        ChemicalElement element = targetBtn.DataContext as ChemicalElement;
        if (element != null)
        {
            string elementInfo = $"原子序数:{element.AtomicNumber}\n" +
                                 $"元素符号:{element.Symbol}\n" +
                                 $"元素名称:{element.Name}\n" +
                                 $"原子量:{element.AtomicWeight}";
            MessageBox.Show(elementInfo);
        }
    }
}

步骤3:修改XAML绑定数据

<Button Grid.Row="5" Grid.Column="2"
        Background="#FF9935"
        BorderBrush="#FF9935"
        Margin="0,0,0,5"
        Click="Button_Click"
        DataContext="{Binding CurrentElement}">
    <Button.Resources>
        <Style TargetType="Border">
            <Setter Property="CornerRadius" Value="5"></Setter>
        </Style>
    </Button.Resources>
    <Grid Height="66" Width="67">
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <!-- 使用数据绑定替代硬编码文本 -->
        <TextBlock VerticalAlignment="Top" Grid.Row="0" FontSize="9" Text="{Binding AtomicNumber}"/>
        <TextBlock VerticalAlignment="Center" Grid.Row="1" FontSize="20" FontWeight="Bold" Text="{Binding Symbol}"/>
        <TextBlock Grid.Row="2" FontSize="10" FontWeight="DemiBold" Text="{Binding Name}"/>
        <TextBlock Grid.Row="3" FontSize="8" Text="{Binding AtomicWeight}"/>
    </Grid>
</Button>

内容的提问来源于stack exchange,提问作者Nazar Buryak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:37:46