'WPF ListView confusing the SelectedItem with equal items
A ListView (or ListBox) with following properties:
<ListView SelectionMode="Single">
<sys:String>James</sys:String>
<sys:String>Claude</sys:String>
<sys:String>Justing</sys:String>
<sys:String>James</sys:String>
</ListView>
will result in selecting two items simultaneously if I click on "James", even though I chose SelectionMode="Single". It's even the same behaviour when I use a helper class with a string-property to display in the ListView. It seems like the ListView is evaluating the Items and selecting those which are Equal() rather than ReferenceEqual(). Is there a way to change this behaviour so that the ListView treats every item individually?
Solution 1:[1]
In order to get the desired behavior, you will need to create a helper class that wraps the string type like this:
public class Item
{
public Item(string name) { Name = name; }
public string Name { get; set; }
}
Using it, you can now do the following:
private ObservableCollection<Item> _items;
public MainWindow()
{
InitializeComponent();
_items = new ObservableCollection<Item>() { new Item("James"), new Item("John"), new Item("Steve"), new Item("Drew"), new Item("Andy"), new Item("James") };
list.ItemsSource = _items;
}
with the XAML like this:
<ListView SelectionMode="Single" x:Name="list" DisplayMemberPath="Name" />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
