ItemsControl of ListViews, bind SelectedItem from

2019-08-22 22:32发布

问题:

I have an ItemsControl with ListViews inside to make a custom grid like layout Here is roughly what the code looks like to do this, names changed and irrelevant styling is removed.

Each ListView is created by an instance of ItemsSubList and therefore there is no set amount of listboxes or properties to be made.

Does anyone know How I would be able to bind the SelectedItem property of each listbox out somehow, into a list preferably.

<ItemsControl ItemsSource="{Binding Items}">
  <ItemsControl.ItemsPanel>
     <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal"/>
     </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>

  <ItemsControl.ItemTemplate>
     <DataTemplate>
         <ListView ItemsSource="{Binding ItemsSubList}" 
                              DisplayMemberPath="ItemVersion" 
                              SelectionMode="Single"
                              Width="100"
                              VerticalAlignment="Top"
                              Background="#282828"
                              BorderBrush="#282828">
         </ListView>
     </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

回答1:

I would solve it in your Model. Your datacontext seems to be a class with a property Items of type ObservableCollection<MyItem> and your class MyItem then as a property ItemsSubList of type ObservableCollection<MySubItem>. Is that right?

The datacontext of your ListView is the instance of type MyItem. You can add a Property SelectedSubItem to your class MyItem and bind it with Two-way-binding to your listbox.SelectedItem.

And then in your main class, that holds your model and where the property Items lives, there I would add a property public List<MySubItem> SelectedSubItems => Items.Select(i => i.SelectedSubItem).ToList();, a property that dynamically selects all selected subitems from all your items.