Multiselect WPF Listbox Make Multiple Selections With a Single Click

biju picture biju · Jul 5, 2009 · Viewed 7.9k times · Source

I have a databound multiselect listbox bound to a datatable. When I select a listboxitem I want some other listboxitems in the same listbox to be selected automatically. I want multiple items to be selected with a single click. How can i do that? I can't do it in SelectionChanged event because it leads to calling the same event again and breaks my logic altogether.

Please help. Any help will be highly appreciated.

UPDATE:

My listbox is already bound to a datatable which has a IsSelected column.I am using the value of this column in a style setter to make the listboxitem selected.Suppose i have 10 rows in the datatable.Now if the user selects the second listboxitem,i can get the isselected of the correspondong row in the database as 1.

But how can i get the other items to select at the same time? I think as Kent said,I rather use a property for binding. But how can i use a property to bind a listbox to a datatable?

Answer

Kent Boogaart picture Kent Boogaart · Jul 5, 2009

Bind IsSelected to a property in your data class. When the property is changed, execute the logic to update the IsSelected property in other data objects:

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="IsSelected" Value="{Binding IsSelected}"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Then in your data class you can have something like this:

public bool IsSelected
{
    get { return _isSelected; }
    set
    {
        if (_isSelected != value)
        {
            _isSelected = value;
            OnPropertyChanged("IsSelected");

            UpdateOtherItems();
        }
    }
}

Or you could have the data item raise an IsSelectedChanged event and have the owning class manage the interdependencies of the selection.