ListBox SelectedItems Binding

wpf listbox
wpf listbox multi-select binding
wpf listbox binding
wpf listbox set selected items
wpf listbox selecteditems behavior
mvvm bind selecteditems
wpf listview selecteditems
listbox selecteditems type

I want to bind Listbox selectedItems to array. But .NET throws exception at runtime.

d.SetBinding(ListBox.SelectedItemsProperty, new Binding { Source = SomeArray });

Where d is some ListBox from XAML.

Exception:

Selected Item cannot be bound.

Why?

You can subscribe to the SelectionChanged event of the ListBox, and in the handler sync a collection of selected items.

In this example the Windows DataContext was set to itself (this) in its constructor. You could also easily call into a logic layer (ViewModel if you're using MVVM) from the event handler.

In Xaml:

<StackPanel>

    <ListBox
        ItemsSource="{Binding ListBoxItems}"
        SelectionMode="Multiple"
        SelectionChanged="ListBox_SelectionChanged">
    </ListBox>

    <ItemsControl
        ItemsSource="{Binding SelectedItems}">
    </ItemsControl>

</StackPanel>

And in the code-behind:

private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    foreach (string item in e.RemovedItems)
    {
        SelectedItems.Remove(item);
    }

    foreach (string item in e.AddedItems)
    {
        SelectedItems.Add(item);
    }
}

WPF ListBox SelectedItems TwoWay Binding, WPF ListBox SelectedItems TwoWay Binding | Alexey Golub. For some unclear reasons, WPF's ListBox control does not allow two-way binding on SelectedItems property the way it does with SelectedItem . This could have been very useful when using multi-select to bind the whole list of selected items to the view model. An application developer can create ListBox controls without specifying the contents of each ListBoxItem separately. You can use data binding to bind data to the individual items. The following example shows how to create a ListBox that populates the ListBoxItem elements by data binding to a data source called Colors.

This is the working solution, however when selection changes SelectedItemsProperty does not refresh bindings...

you can create a custom control as follow

public class MyListBox: ListBox{

    public MyListBox()
    { 
         this.SelectionChanged += (s,e)=>{ RefreshBindings(); };
    }

    private void RefreshBindings()
    {
         BindingExpression be = 
             (BindingExpression) GetBindingExpression(
                                      SelectedItemsProperty);
         if(be!=null){
               bd.UpdateTarget();
         }
    }

}

or in your app you can define event in every listbox as shown below ..

myListBox.SelectionChanged += (s,e) => {
    BindingExpression be = 
         (BindingExpression) myListBox.GetBindingExpression(
                                      ListBox.SelectedItemsProperty);
    if(be!=null){
        bd.UpdateTarget();
    }
};

Accessing WPF ListBox SelectedItems using MVVM, <ListBox ItemsSource="{Binding Items}" SelectionMode="Extended" to bind an ObservableCollection directly to the SelectedItems property of� EDIT: from my reading, it seams that listboxes couldn't 'easily' bind 'SelectedItems'..maybe then a solution to bind to a checkbox component inside the listbox item? Thanks for any kind help! Edited by jmdeb Sunday, March 24, 2019 11:03 AM

ListBox.SelectedItems is read-only. Did you mean to bind to ListBox.SelectedItem instead?

ListBox.SelectedItems Property (System.Windows.Controls , I am developing a UI using the Model-View-ViewModel pattern. I have a situation where I need to keep a list of SelectedItems in sync between� I want to bind Listbox selectedItems to array. But .NET throws exception at runtime. d.SetBinding(ListBox.SelectedItemsProperty, new Binding { Source = SomeArray }); Where d is some ListBox from

I am not sure if I understand your question correctly or the exact scenario - but assuming you wanted to have one listbox "d" show the items that were selected in another listbox "MyOtherListbox" then you just need to set the binding mode to 'one way' else it will bring up an error.

You could do something like

d.SetBinding(ListBox.ItemsSourceProperty, new Binding { Source = MyOtherListbox.SelectedItems, Mode = BindingMode.OneWay});

Binding a ViewModel to ListBox SelectedItems - MSDN, A behavior that allows the developer to bind an IList to SelectedItems of a ListBox or MultiSelector. <ListBox ItemsSource= "{Binding Items}" SelectionMode= "Extended" SelectedItems= "{Binding SelectedItems}" /> One-way To Presenter If we only care about setting the selected items from the View and operating on it when a command it executed, we can do this relatively simply.

my trick: in xaml, use MultiBinding, force execute converter in Count property change (it work!).

<MultiBinding Converter="{StaticResource SelectedRowsTotal }">
    <Binding Path="SelectedItems"  ElementName="listBox1" />
    <Binding Path="SelectedItems.Count"  ElementName="listBox1" />
</MultiBinding>

Converter:

public class SelectedRowsTotal : IMultiValueConverter 
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 
    {
        var selecteds = values as IEnumerable;

        if (selected == null) 
            return null;

        return selecteds.Cast<SomeType>().Sum(x=> x.SomeProperty) = total;
    }

    object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) 
    {
        return null;
    }
}

SelectedItems Behavior for ListBox and MultiSelector, had a way of data-binding the SelectedItems property of a ListBox. of selected items to prove that the data binding is working correctly. Binding to the selected items of a ListBox (or an another items controls) 13 June 2010 A problem you often meet when using MVVM is to get the selected items of an items control, especially Listbox.

How to Databind to a SelectedItems property in WPF, wpf listbox selecteditem binding, This happens because the SelectedItem property of the ListBox is an instance of Player when you specify an ItemsSource as� Hi, I am using ReactiveUI 6.4.0.1 I am trying to bind a property in my ViewModel with the selectedItem event in a ListBox View: this.WhenAnyValue(v =&gt; v.ItemsListBox.SelectedItem).BindTo(_vm, vm

How to support ListBox SelectedItems binding , WPF binding to Listbox selectedItem, First off, you need to implement INotifyPropertyChanged interface in your view model and raise the PropertyChanged event� WPF ListBox class represents a ListBox control that is a collection of ListBoxItems. The <ListBox> XAML represents the UI of a ListBox. This tutorial and code examples are the various use cases of ListBox control in WPF and C#, such as ListBox Formatting, ListBox Style, Images in ListBox, CheckBox in ListBox, and Data Binding in ListBox.

The ListBox control, Learn all about the WPF ListBox control in this chapter, loaded with examples and By default, if you bind a list of items to the ListBox, their ToString() method will be SelectedItem = o; break; } } } private void btnSelectAll_Click(object sender,� Basic MVVM pattern for binding items to a listbox in WPF, this pattern can also be used for Winforms just how you set the control will be done in code behind. Background. This example shows how to bind items from a directory to a listbox. You can use the same methodology to bind any collection to the listbox.

Comments
  • This seems to work as OneWayToSource binding. If I change the SelectedItems collection, then the changes are not reflected in the listbox.
  • @BogdanVerbenets Maybe setting Mode to TwoWay and UpdateSourceTrigger to PropertyChanged will do the trick? By the way, we have the same first name! :D
  • Downvoted because suggesting the use of an event handler in code-behind to call into a view model doesn't follow the MVVM pattern. If you don't mind code-behind (and I do mind it, but whatever), then use this. But please, don't pollute view models by calling into them from code-behind.
  • No I have several selected items and I want to show them in ListBox in selected state
  • Since that property is read-only, you can't use it for what you want. The only thing I can think of is to set individual ListBoxItem.IsSelected properties. If you insist on binding, the easiest path would be for you to create e.g. an attached SelectedItems DependencyProperty with custom logic in property changed event handler.
  • I must use something Like this: d.SetBinding(ListBox.SelectedItemsProperty, new Binding { Source = SomeArray, Mode=OneWay }); But it raise the same exception.
  • No, you cannot bind to the SelectedItemsProperty since it only has a get accessor. I think the closest you will get to this is if you read the following thread... social.msdn.microsoft.com/Forums/en-US/wpf/thread/…
  • This will not refresh if selected items are changed, because SelectedItems is List and not an observable collection or binding list.
  • Thanks Polaris - does that mean the thread answered your question?