c# - 如何在代码隐藏中访问 Button.Content 中的控件?

标签 c# wpf button controls

在 XAML 中,我创建了一个这样的按钮:

<Button MouseEnter="Button_MouseEnter">
    <Button.Content>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>

            <TextBlock Grid.Row="0" Text="asd"/>
            <Label Grid.Row="1" Content="xxx"/>
            <Label Grid.Row="2" Content="yyy"/>
        </Grid>
    </Button.Content>
</Button>

现在我需要在代码隐藏中访问 Button 内容中的其中一个控件。假设我需要一个 TextBlock。

private void Button_MouseEnter(object sender, MouseEventArgs e)
    {
        Button button = (Button)sender;
        // ? 
    }

我该怎么做? 我还有多个像这样的按钮通过数据绑定(bind)自动创建。 我需要访问这些控件的原因是我想在特定情况下为其中之一设置动画。

最佳答案

        private void Button_MouseEnter(object sender, MouseEventArgs e)
    {
        Button b = sender as Button;
        TextBox textBox = null;
        if (b != null)
        {
            foreach (var frameworkElement in ((Grid)b.Content).Children)
            {
                if (frameworkElement is TextBox)
                {
                    textBox = (TextBox)frameworkElement;
                    break;
                }
            }

        }
    }

这只是为了说明如何提取作为按钮内容的 Grid 的子项。我希望这会帮助您了解这个想法。

关于c# - 如何在代码隐藏中访问 Button.Content 中的控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11645314/

相关文章:

c# - Windows 工作流延迟 Activity 行为

wpf - Visual Studio 2008 : Setting the vertical separation to default in wpf designer

c# - 我实际上如何从方法外部获得异步 Web 请求的响应?

c# - 如何定位窗口内的所有按钮?

c# - 单击时更改按钮颜色(多次单击/颜色)

c# - 想要以与保存在 C# windowsForm 中相同的格式读取从数据库检索的文件

c# - 如何以编程方式设置 UITableViewCell 中显示的文本

c# - 从文本文件中删除一些特殊的词

c# - 如何将 XAML 代码从 Window 移动到 Application.Resources

c# - 当控件不可见时,MouseHover 和 MouseLeave 不起作用