代码之家  ›  专栏  ›  技术社区  ›  user1336827

单击组名时,CollectionViewSource未选中selectedItem

  •  2
  • user1336827  · 技术社区  · 10 年前

    我有一个 listbox 有它的 itemSource 绑定到 collectionViewSource 其被分组并且在实际项目上具有2级分组:

            <ListBox ItemsSource="{Binding Source={StaticResource myCVS}}" ItemTemplate="{StaticResource myItemsTemplate}" ItemContainerStyle="{StaticResource myItemsStyle}" SelectedItem="{Binding SelectedListItem}" >
                <ListBox.GroupStyle>
                    <GroupStyle ContainerStyle="{StaticResource HeaderStyle}" />
                    <GroupStyle ContainerStyle="{StaticResource SubHeaderStyle}" />
                </ListBox.GroupStyle>
            </ListBox>
    

    用一个 CollectionViewSource 绑定到 ObservabeleCollection :

           <CollectionViewSource x:Key="myCVS" Source="{Binding Path=myItemsToGroup}">
                <CollectionViewSource.GroupDescriptions>
                    <PropertyGroupDescription PropertyName="HeaderName" />
                    <PropertyGroupDescription PropertyName="SubHeaderName" />
                </CollectionViewSource.GroupDescriptions>
            </CollectionViewSource>
    

    中的项目 ObservalbleCollection 看起来像:

    public class Items
    {
        public string GroupName;
        public string SubGroupName;
        public string ItemName;
    }
    

    这一切都很好,我最终得到了:

    Header1
     |_SubHeader1
         |_item1
         |_item2
    Header2
     |_SubHeader2
         |_item1
         |_item2
    

    问题是,如果我单击一个项目,它就会被选中,如果我点击标题或子标题,它就会保持选中状态。如果单击标题,我希望设置 SelectedItem 设置为空。我正在使用命令删除 所选项目 但我不想在只有在单击项目时才单击标题或子标题的情况下执行该命令。

    1 回复  |  直到 10 年前
        1
  •  2
  •   Kcvin    10 年前

    GroupStyle s是不可选择的,因此您的视图模型当然不会看到选择更改发生。

    要解决这个问题,可以使用一些代码隐藏。如果您单击 ListBox 然后 ListBoxItem 将设置MouseUp事件的 Handled 属性设置为true。如果您单击 列表框 ,没有任何内容处理该事件。话虽如此,您可以根据 已处理 .

    XAML:

    <ListBox ItemsSource="{Binding Source={StaticResource myCVS}}"
             ItemTemplate="{StaticResource myItemsTemplate}"
             ItemContainerStyle="{StaticResource myItemsStyle}"
             SelectedItem="{Binding SelectedListItem}"
             MouseLeftButtonUp="ListBox_MouseLeftButtonUp">
    

    后面的代码:

    private void ListBox_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if(!e.Handled)
        {
            var lb = sender as ListBox;
            lb.SelectedItem = null;
        }
    }
    

    附录:

    单击已选择的项将将SelectedItem设置为空。要防止这种情况,请执行以下操作:而不是使用 MouseLeftButtonUp 使用 MouseDown:

    <ListBox ItemsSource="{Binding Source={StaticResource myCVS}}"
             SelectedItem="{Binding SelectedListItem}"
             MouseDown="ListBox_MouseLeftButtonUp">
    

    Here 是我当前应用程序的状态( 组样式 ’s)绘制得不正确,但实现才是最重要的。如果这不适合您,我将实现纯MVVM方法。