简体   繁体   中英

MVVM - get selected items from ListBox via Data Binding

I am writing app using MVVM pattern in C#.

My goal is to get selected items from ListBox in my own User Control.

I have created bindable object, with method to change this object (called when something new is selected):

public partial class MyUserControl : UserControl
{
    ...

    public IEnumerable SelectedItems
    {
        get { return (IEnumerable)GetValue(SelectedItemsProperty); }
        set { SetValue(SelectedItemsProperty, value); }
    }
    public static readonly DependencyProperty SelectedItemsProperty =
        DependencyProperty.Register("SelectedItems", typeof(IEnumerable),
            typeof(MyUserControl),
            new FrameworkPropertyMetadata(default(IEnumerable),
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public MyUserControl ()
    {
        InitializeComponent();
    }

    private void SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        SelectedItems = ListBox.SelectedItems;
    }
}

There is also Items part, and in xaml part ListBox is named ListBox:

<ListBox Name="ListBox" SelectionChanged="SelectionChanged" ... />

This how it looks in page with ViewModel, in which MyUserControl is created:

<uc:MyUserControl ... SelectedItems="{Binding Path=MyObjectItems}" />

And here comes the problem. When setting SelectedItems in ViewModel:

private ObservableCollection<MyObject> _myObjectItems;

public ObservableCollection<MyObject> MyObjectItems
{
    get { return _myObjectItems; }
    set { _myObjectItems = value; }
}

No matter what I do, value will always be null. This also means, that SelectedItems in MyUserControl is null, too.

I can, for example use OneWayToSource binding mode:

<uc:MyUserControl ... SelectedItems="{Binding Path=MyObjectItems, Mode=OneWayToSource}" />

value is still null, same as MyObjectItems , but at least SelectedItems in MyUserControl contains selected items. Not good enough :/

After hours of trying different approaches I've found NuGet package Extended WPF Toolkit . List SelectedItemsOverride from class CheckListBox allows to bind list of selected items:

<UserControl x:Class="View.UserControls.MyUserControl"
             ...
             xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
             x:Name="Root">
   <Grid>
      <xctk:CheckListBox Name="ListBox"
          ItemSelectionChanged="SelectionChanged"
          SelectedItemsOverride="{Binding SelectedItems, ElementName=Root}"
          ... />
   </Grid>
</UserControl>

And because of that, binding:

<uc:MyUserControl ... SelectedItems="{Binding Path=MyObjectItems}" />

works! I have access to selected items in View Model - everything in simple way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM