2

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.

Each ListView has its SelectedItem property bound to the same property in the ViewModel.

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>
sk_
  • 2,105
  • 17
  • 31
  • Does `MySelectedItem` property raises `INPC.PropertyChanged` event when changed? – dkozl Jan 17 '15 at 16:34
  • Yes, the PropertyChanged event is fired in the setter of this property. – sk_ Jan 17 '15 at 16:38
  • and `MySelectedItem` is one property for both `ListView`'s, is defined in the same class as `MyList1` and `MyList2` and you confirmed in debugger that setter is called when you select something in either `ListView`? – dkozl Jan 17 '15 at 16:44
  • MySelectedItem is declared as an object and the two lists contain different object types. Everything works fine from a viewmodel point of view, the problem is just the selection in the view. – sk_ Jan 17 '15 at 16:47
  • Do `MyList1` and `MyList2` contain the same instances of items? – user2250152 Jan 17 '15 at 17:45
  • No. As stated above, the two list are from different classes. – sk_ Jan 17 '15 at 18:09

2 Answers2

5

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.

sk_
  • 2,105
  • 17
  • 31
0

You need to use Mode=TwoWay in your SelectedItem. It should work.

RenDishen
  • 928
  • 1
  • 10
  • 30
  • Selecteditem in an itemscontrol binds two way by default. You're basically forcing the default value. – sk_ Jan 17 '15 at 18:48