Search code examples
wpfdata-bindingcomboboxdependency-properties

Binding 'SelectedItems' dependency property to ViewModel property does not work


I have a multiselect Combobox usercontrol and a dependency property 'SelectedItems'. I m trying to use the usercontrol and bind the 'SelectedItems' to another property called 'SelectedResultItems' in my ViewModel. But I dont get any values to SelectedResultItems. Please help

Here is what i tried.

My main xaml:

    <DataTemplate x:Key="TypeATemplate">
<control:MultiSelectComboBox Width="315" ItemsSource="{Binding 
ResultvalueList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
SelectedItems="{Binding 
SelectedResultItems,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>

My Combobox usercontrol code behind:

public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register("SelectedItems", 
typeof(ObservableCollection<string>), typeof(MultiSelectComboBox), new 
FrameworkPropertyMetadata(null,new 
PropertyChangedCallback(MultiSelectComboBox.OnSelectedItemsChanged)));

public ObservableCollection<string> SelectedItems
{
get { return 
(ObservableCollection<string>)GetValue(SelectedItemsProperty); }
set
{
SetValue(SelectedItemsProperty, value);
}
}

I am setting the 'SelectedItems' on click of the checkbox.

My mainviewmodel:

public ObservableCollection<string> SelectedResultItems
{
get => _selectedResultItems;
set
{
_selectedResultItems = value;
NotifyPropertyChanged(nameof(SelectedResultItems));
}
}

Solution

  • If this is the same as for ListView(never used MultiSelectCombobox), you cannot bind to SelectedItems because it is a read-only property.

    What I did to solve that is add the event SelectionChanged to ListView(or MultiSelectCombobox for you).

    Then event would be :

    private void YourComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
       {
          contexte.ResultItems = YourComboBox.SelectedItems.Cast<YourItem>().ToList();
       }
    

    Maybe there is a different way to do it, but until now that's the easiest way I found.