views:

284

answers:

1

Hello.

In my XAML file, I have a ListBox declared like this :

           <ListBox x:Name="lstDeck" Height="280" ItemsSource="{Binding Path=Deck}"  >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <ListBoxItem  Content="{Binding}" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

In my view model, Deck is an ObservableCollection, so that binding directly displays the content of my collection.

But when I have several value that hold the same value (for example "10" six times), the selection in the ListBox has a weird behaviour : it select 2-3 elements instead of the only the one on which I clicked.

Moreover, when I click to another listBoxItem, it doesn't unfocus the previous selected one.

Then it is impossible to see which item is actually selected, and impossible to get the SelectedIndex value.

Has someone an idea?

+5  A: 

The problem is that the listbox cannout distinguish between the different values. Therefore, once you click one of the "10"s, it sets it SelectedItem property and updates its presentation. Because it cannot distinguish between the value types it marks every "10" as selected.

But why do you have "10" several times in your listbox? If it is just the numeric value 10 or the string "10" it does not make any sense to me.

If you have a more complex model behind that and you just display one property, than you should bind the complex model and set the DisplayMemberPath instead.

C#

public class Model
{
    public Guid Id { get; set; }
    public string Value { get; set; }
}

XAML

<ListBox ItemsSource="{Binding Path=Models}" DisplayMemberPath="Value" />

<ListBox ItemsSource="{Binding Path=Models}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=Value}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Best Regards
Oliver Hanappi

Oliver Hanappi
it displays the number 10, but that is just an example.in practice, I have a listbox that displays a collection of game Card, and an other that displays IDs of these card added to a deck.Since it is possible to have 3-4 time the same card, it is possible to have several time the same value.Here is my problem.
KiTe
I see your problem. Turn your card struct into a class. So, the user will see the same card twice but internally it won't be the same (reference equality versus value equality). Make sure that you don't override the Equals and GetHashCode method in a way that implements value equality.
Oliver Hanappi
Oliver is correct. Your listbox is using the number "10" as the key for your objects. Since you have multiple "10"s, all of them are selected. You need to have something to distinguish them, hence the object he suggested above.
Darien Ford
I just did it and it works, thank you =]
KiTe