在两个ListView中仅选择一项 [英] Select only one item in two ListViews
问题描述
我有两个 ListView
,每个都绑定到ViewModel中的特定集合,并且我希望只能在全局范围内选择一个项目.
I have two ListView
, each bound to a specific collection in my ViewModel and I want to be able to select only one item globally.
每个 ListView
的 SelectedItem
属性都绑定到ViewModel中的相同属性.
Each ListView
has its SelectedItem
property bound to the same property in the ViewModel.
我的问题如下:当我在 ListView
中选择一个项目,然后在另一个 ListView 中选择另一个项目时,第一个项目保持选中状态.我可以通过一些隐藏的代码来实现,但是我想知道是否存在纯XAML解决方案.
My probleme is as follow: when I select an item in a ListView
, and then select another item in the other ListView, the first item stays selected.
I could achieve this with some code-behind, but I want to know if a pure XAML solution exists.
XAML:
<ListView SelectionMode="Single" ItemsSource="{Binding Path=MyList1}" SelectedItem="{Binding Path=MySelectedItem}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<ListView SelectionMode="Single" ItemsSource="{Binding Path=MyList2}" SelectedItem="{Binding Path=MySelectedItem}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
推荐答案
我终于通过将 SelectedItem
替换为 SelectedValue
来使它正常工作.
I finally got it working, by just replacing SelectedItem
by SelectedValue
.
在此用例中,两个属性具有相同的行为,但是如果绑定的选定项不在列表中,则后一个属性可以正确处理取消选择.
In this use case, both properties have the same behaviour, but the latter one handles correctly the unselection if the bound selected item is not in the list.
这篇关于在两个ListView中仅选择一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!