Can i create SelectedItems Property for multiselect combobox

1.5k views Asked by At

Currently I am working on multiselect combobox custom control with combobox inherited, which attached a listbox to a combobox with a multiple selection mode. But now I face a problem when passing the selected items to my custom control in view. I use the listbox selectionchanged event to update my selected item in my combobox. I'm able to implement this approach on selecteditem, it manages to pass one selected item to my view. But I want to pass all the selecteditems to my view. And this is what I have done so far.

MultiSelectCombobox.xaml <-- My custom control xaml inherited from combobox

<ComboBox.Template>
...
<Popup>
    <ListBox SelectionMode="Multiple" ItemsSource="{TemplateBinding ItemsSource}" 
    SelectionChanged="ListBox_SelectionChanged">
     ...
    </ListBox>
</Popup>

MultiSelectCombobox.xaml.cs

   public partial class MultiSelectComboBox : ComboBox
...
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ListBox lb = sender as ListBox;
    this.SelectedItem = lb.SelectedItem;
}

MainWindow.xaml.cs

MultiComboBox mComboBox = (sender as MultiComboBox);
MessageBox.Show(this, mComboBox.SelectedItem.ToString());

use this 2 line in some combobox event to display selecteditem.

I search through few posts, but I'm still unable to find any solution, I would appreciate if you could provide some guidance for me.

1

There are 1 answers

0
almulo On BEST ANSWER

Try this...

MultiSelectCombobox.xaml.cs

public partial class MultiSelectComboBox : ComboBox
{

    ...

    public static readonly DependencyProperty SelectedItemsProperty =
        DependencyProperty.Register("SelectedItems", typeof(IList),
        typeof(MultiSelectComboBox));

    private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListBox lb = sender as ListBox;
        this.SelectedItem = lb.SelectedItem;
        this.SelectedItems = lb.SelectedItems;
    }

}

Keep in mind that this would only work for one way selection. If you want to make sure it is only used to get the selected items and that nobody tries to set them this way, you could turn the DependencyProperty into a readonly one and use an IEnumerable instead of an IList.

If you wanna support two way selection changes (changing the selected items from code and not only from user interaction with the ListBox) then you'd have to add a property changed callback to the DependencyProperty and maybe use an ObservableCollection to listen for changes in the collection, and update the ListBox selection accordingly.