因此,我有几个要在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: TextBlocks属性来获取文本块,但问题是我现在有一个巨大的文本块列表,我怀疑唯一的方法是输入每个文本块的名称。如果有人能澄清他们将如何处理这件事?简单的解决方案会更好,我是一个新手程序员,这是一个学校的项目。
发布于 2013-05-12 23:59:04
如果你需要引用很多控件,你可以将它们分组到一个控件中(stackpanel,grid,...)并通过枚举容器的子控件来访问控件。
另一种选择是use data binding。这样一来,您可能根本不需要引用控件。
发布于 2013-05-12 20:43:01
使用方法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
}https://stackoverflow.com/questions/16507452
复制相似问题