0

所以我有几个要在我的 c# 类中使用的元素。这些是我想要从中提取元素的 xaml 文档的几行:

    <TextBlock x:Name="diastolic17" FontSize="10" Foreground="Ivory" Grid.Row="19"
             Grid.Column="4"
             TextAlignment="Center">0</TextBlock>
    <TextBlock x:Name="diastolic18" FontSize="10" Foreground="Ivory" Grid.Row="20"
             Grid.Column="4"
             TextAlignment="Center">98</TextBlock>
    <TextBlock x:Name="diastolic19" FontSize="10" Foreground="Ivory" Grid.Row="21"
             Grid.Column="4"
             TextAlignment="Center">88</TextBlock>

它们都在同一个命名空间中。我以前只使用 x:Name 属性来获取 TextBlocks,但问题是我现在有一个庞大的 TextBlocks 列表,我怀疑唯一的方法是输入每个 Textblock 的名称。如果有人能澄清他们将如何处理这个问题?简单的解决方案会被优先考虑,我是一个新手程序员,这是一个学校项目。

4

2 回答 2

1

使用方法FindVisualChildren。它遍历 Visual Tree 并找到您想要的控件。

这应该可以解决问题

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
        if (child != null && child is T)
        {
            yield return (T)child;
        }

        foreach (T childOfChild in FindVisualChildren<T>(child))
        {
            yield return childOfChild;
        }
    }
}
}

然后你像这样枚举控件

foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
    // do something with tb here
}
于 2013-05-12T12:43:01.037 回答
0

如果您需要引用很多控件,您可以将它们分组到单个控件(堆栈面板、网格等)中,并通过枚举容器的子控件来访问这些控件。

另一种方法是使用数据绑定。这样,您可能根本不需要参考控件。

于 2013-05-12T15:59:03.740 回答