我有一个 listbox
,其 itemSource
绑定(bind)到 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
绑定(bind)到 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
设置为 null。我正在使用命令从 UI 中删除 SelectedItem
,但如果仅在单击某个项目时单击标题或子标题,我不希望执行该命令。
最佳答案
GroupStyle
是不可选择的,因此您的 View 模型当然不会看到选择发生更改。
要解决此问题,您可以使用一些隐藏代码。您会注意到,如果单击 ListBox
中的项目,则 ListBoxItem
会将 MouseUp 事件的 Handled
属性设置为 true。如果您单击 ListBox 上的任何其他位置,则不会处理该事件。话虽如此,您可以根据 Handled
的状态设置所选项目。
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 设置为 null。为了防止这种情况,请执行以下操作:不要使用 MouseLeftButtonUp
,而是使用 MouseDown:
<ListBox ItemsSource="{Binding Source={StaticResource myCVS}}"
SelectedItem="{Binding SelectedListItem}"
MouseDown="ListBox_MouseLeftButtonUp">
Here是我当前应用程序(GroupStyle
's)的状态没有正确绘制,但这里的实现才是重要的。如果这不适合您,我将实现纯 MVVM 方法。
关于wpf - 单击组名称时 CollectionViewSource 取消选择 selectedItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29259701/