使用扩展器样式绑定到CollectionViewSource

时间:2015-04-08 16:19:18

标签: wpf binding collectionviewsource

CollectionViewSource绑定了ObservableCollection ViewModels。然后我在style上有一个GroupItem,其中有一个expander。我希望能够在群组标题上进行“全部折叠”和“全部展开”,但无法绑定isExpanded expander上的ControlTemplate。我有这段代码:

      <Style x:Key="GroupStyle" TargetType="{x:Type GroupItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type GroupItem}">
                        <Expander IsExpanded="{Binding Path=**????**}" Template="{StaticResource DAExpander}">
                            <Expander.Header>
                                <DockPanel VerticalAlignment="Center">
                                    <Image DockPanel.Dock="Left" x:Name="scItemIcon" Source="./groupIcon.ico" Height="18" Width="18"/>
                                    <TextBlock DockPanel.Dock="Left" Text="{Binding Name}"  VerticalAlignment="Center"  Margin="4,0,6,0" />
                                </DockPanel>
                            </Expander.Header>
                            <ItemsPresenter />
                        </Expander>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

我的视图模型上有一个IsExpanded属性,但我无法弄清楚如何访问它。我找到了例如:

<Expander IsExpanded="{Binding Path=Items[0].IsExpanded}" 
<Expander IsExpanded="{Binding Path=Name.IsExpanded}" 

这些似乎都不起作用。有没有办法实现这一点,还是我需要采取不同的方法?

修改:更多xaml,并查看模型代码:

           <ListBox  ItemsSource="{Binding Source={StaticResource MyCVS}}" ItemTemplate="{StaticResource ItmesTemplate}" ItemContainerStyle="{StaticResource ItemChildStyle}" SelectedItem="{Binding SelectedItem}" >
                <ListBox.GroupStyle>
                    <GroupStyle ContainerStyle="{StaticResource GroupStyle}" />
                    <GroupStyle ContainerStyle="{StaticResource Group2Style}" />
                </ListBox.GroupStyle>
            </ListBox>



public class ItemViewModel : ViewModelBase
    {   
        public string GroupName { get; set; }
        public string SubGroupName{ get; set; }
        public string ItemName { get; set; }
        public bool IsExpanded {get; set;}
    }

1 个答案:

答案 0 :(得分:0)

我在没有约束的情况下解决了这个问题,方法是点击我的&#39;展开全部&#39;按钮

private void expandAll_Click(object sender, EventArgs e)
{
    // get each listBoxItem by index from the listBox
    for (int i = 0; i < MyListBox.Items.Count; i++)
    {
        ListBoxItem item = (ListBoxItem)MyListBox.ItemContainerGenerator.ContainerFromIndex(i);

        // find its parents expander
        var exp = FindParent<Expander>(item);

        if (exp != null)
        {
            //if its not null expand it and see if it has a parent expander
            exp.IsExpanded = true;
            exp = FindParent<Expander>(exp);
            if (exp != null)
                exp.IsExpanded = true;
        }

    }
}

FindParent函数是一个帮助程序,它在可视树中向上查找从您传入的控件开始指定的控件。