有没有办法获得UIElementCollection中的项目?

时间:2011-08-12 15:55:29

标签: c# wpf collections

我在网格中有一堆CheckBoxes。我想访问它们,以便我可以根据启动时的注册表值将它们设置为选中或取消选中。

我已将Grid的子项作为UIElementCollection,并过滤掉其他类型..但是,似乎没有任何方法可以访问存储在集合中的数据。这样做有简单的方法吗?

2 个答案:

答案 0 :(得分:5)

UIElementCollectionIEnumerable,所以你可以循环它......

foreach( UIElement child in myUIElementCollection)
{
}

答案 1 :(得分:1)

通过类型或任何可以使用VisualTreeHelper的方式简化对控件的搜索,并以这种方式遍历元素:

foreach (UIElement childElement in myUIElementCollection) 
{
  for (int i = 0; i < VisualTreeHelper.GetChildrenCount(childElement); i++)
  {
     DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
     var checkBox = child as CheckBox;
     if (checkBox != null)
     {
         // update it
     }
  }
}

BTW,为什么不暴露像IsRegistryValueFound这样的布尔属性,只是将它绑定到CheckBox.IsChecked中的XAML属性?