简体   繁体   中英

Databinding the ListBox SelectedItems attribute

I know that the ListBox has both a SelectedItem and SelectedItems attribute and that only the SelectedItem attribute can be used with databinding. However, I've read in multiple locations that by setting up a setter like so

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

and then by adding the following property

public IEnumerable<Item> SelectedItems
{
     get
     {
          return Items.Where(x => x.IsSelected);
     }
}

I can use the SelectedItems property to get the all items that were selected. I mainly have two questions regarding this:

  1. Where does the Item and Items in the property come from? I've not been able to find a using directive that will remove the error preventing me from using it.

  2. Is this the recommended way to do what I'm trying to achieve. If not, then what would you recommend?

Oh, before I forget I thought I should mention that I'm using both MVVM Light and Fody's PropertyChanged.

I'm not quite sure about the articles and their exact solution for doing so but my speculations is this:

  1. The whole page has a ViewModel named MyPageViewModel .
  2. MyPageViewModel has an ObservableCollection named Items .
  3. Item is ViewModel type (derived from DependencyObject )
  4. Item has a DependencyProperty named IsSelected

Given these assumptions you can see where can all things fit.


If the DataContext of the whole page is MyPageViewModel , then in this xaml code first IsSelected refers to a property of ListBoxItem , and the second one refers to a property in ViewModel of Item .

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

//This is inside MyPageViewModel
//Item is a ViewModel type
public IEnumerable<Item> SelectedItems
{
     get
     {
          //Items is ObservableCollection<Item>
          return Items.Where(x => x.IsSelected);
     }
}

//This is also inside MyPageViewModel
private ObservableCollection<Item> _items = new ObservableCollection<Item>();
public ObservableCollection<Item> Items { get { return _items; } } 

The whole scenario can go the other way too. I mean it can be implemented in View instead of ViewModel. Maybe derive from ListBox and override a few things including SelectedItems . But adding these sorts of complexities are better done to ViewModel than View.

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