ListBox selector odd behavior when there are dupes

Posted by byte1918 on Stack Overflow See other posts from Stack Overflow or by byte1918
Published on 2010-03-13T16:40:13Z Indexed on 2010/03/13 16:45 UTC
Read the original article Hit count: 288

Filed under:
|

I'm working on a bigger project atm, but I made this simple example to show you what happens..

using System.Collections.Generic;
using System.Windows;
namespace txt
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var obsLst = new List<Info> { new Info { name = "asd" }, new Info { name = "asd" }, new Info { name = "asd" }, new Info { name = "asd" } };
            var temp = new List<Info>();
            for (var i = 1; i <= 3; i++)
            {
                temp.Add(obsLst[0]); //I add 3 of the same item from obsLst to temp
            }
            lst.DataContext = temp; //lst = ListBox
        }
    }
    public class Info
    {
        public string name { get; set; }
    }
}

The ListBox ItemsSource is set to {Binding}..

When I start the application I get 3 txt.Info objects displayed and if I click any of them, 2 or even all of them get selected aswell. From my understanding the problem relies in the fact that the listbox selector cannot differentiate between the items and therefor doesn't know which one I selected.

Here's a picture of what it looks like.. alt text

I only clicked on the second txt.Info item.

I found a solution where someone said that I have to specify the DisplayMemberPath, but I can't really do that in the other project because I have a datatemplate for the object.

Any ideas on how I could fix this would be great..

Thx in advance.

© Stack Overflow or respective owner

Related posts about wpf

Related posts about c#