ListBox not updating on SelectedItems.Add()

1.6k Views Asked by At

I'm trying to bind a multiple selection listbox to a list<int>(IdProv) I have. what I do is binding the SelectedValue to a property that adds or removes that value to the list<int>. both list<int> and listbox.SelectedItems should be synchronized.

The listbox's xaml code looks like this:

            <ListBox DisplayMemberPath="Name"
                     SelectedValuePath="Id"
                     SelectedValue="{Binding Path=IdProv,
                                    Mode=OneWayToSource,
                                    ValidatesOnExceptions=True}"
                     SelectionMode="Multiple" />

the ItemsSource is set in the code-behind. it's a list of products that have an Id and a Name property

the problem resides in the SelectedValue property that doesn't get updated correctly (neither SelectedItem). They are setted only when the first item is selected, but then they get updated.

also when selecting an item making a click on the list, the SelectedValue just updates when I click the item that was first added.

any idea what's going on? I'm sure I made a silly mistake in bindings, but this took me hours and I can't figure it out!

thanks, Martín

1

There are 1 best solutions below

0
On

I made a simple hack, which i'm not happy with, but resolves the problem. I wrote this SelectionChanged handler that takes care of setting the property that SelectedValue isn't updating:

    private void idProveedorListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListBox list = (ListBox)sender;
        if (list.SelectedItems.Count == 0)
        {
            ProdList.Last().IdProv.Clear();
            return;
        }
        else
        {
            Models.Proveedor lastSelected = list.SelectedItems[list.SelectedItems.Count - 1] as Models.Proveedor;
            if (lastSelected != list.SelectedItem)
                PProdList.Last().IdProveedorInt = lastSelected.Id;
        }
    }