通过DataTemplate访问ItemsControl中生成的控件

时间:2012-08-10 13:30:49

标签: c# wpf itemscontrol

以下是生成按钮列表的标记。

 <ItemsControl x:Name="Items" Grid.Row="5"  Grid.ColumnSpan="2">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Vertical"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <ToggleButton Content="{Binding Name}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

使用过滤条件

对按钮应用了过滤
 collectionView = (CollectionView)CollectionViewSource.GetDefaultView(Items.ItemsSource);
 collectionView .Filter = FilterList;

问题是当我切换过滤器状态时,我想保留按钮状态。我已经尝试订阅事件StatusChanged

Items.ItemContainerGenerator.StatusChanged += new System.EventHandler(ItemContainerGenerator_StatusChanged);

但似乎没有在状态为ContainersGenerated

时生成控件
void ItemContainerGenerator_StatusChanged(object sender, System.EventArgs e)
{
  if (Items.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
            {
                RefreshButtons();
            }    
}

1 个答案:

答案 0 :(得分:0)

访问它们的唯一方法是使用VisualTree。 只需使用这样的东西:

public static T[] FindVisualChilds<T>(DependencyObject parent, Func<DependencyObject, bool> CompareDelegate)
    where T : DependencyObject
{
    if (VisualTreeHelper.GetChildrenCount(parent) == 0) return null;
    List<T> childs = new List<T>();

    if (CompareDelegate(parent))
        childs.Add(parent as T);

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        var tmp = FindVisualChilds<T>(VisualTreeHelper.GetChild(parent, i), CompareDelegate);
        if (tmp != null)
            childs.AddRange(tmp);
    }
    return childs.ToArray();
}

现在作为firstparameter传递您的数据网格,并作为第二个委托,检查控件是否是您想要的控件。因此,您将获得所有控制权