简体   繁体   中英

Binding to a collection of child ViewModels in XAML

I have a domain model that looks like this:

* Parent
  * ParentProperty1
  * ParentProperty2
  * Children (an array of Child objects)
* Child
  * ChildProperty1
  * ChildProperty2

I have a created a custom ChildUserControl that binds to a child via a ChildViewModel . My main window is bound to a ParentViewModel and contains a WrapPanel that displays one ChildUserControl for each child owned by that parent.

The XAML for the panel is:

  <ItemsControl ItemsSource="{Binding Children}">
      <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
              <WrapPanel />
          </ItemsPanelTemplate>
      </ItemsControl.ItemsPanel>
      <ItemsControl.ItemTemplate>
          <DataTemplate>
              <editor:ChildUserControl DataContext="{Binding}" />
          </DataTemplate>
      </ItemsControl.ItemTemplate>
  </ItemsControl>

The problem with this is that it sets the DataContext of each ChildUserControl to a raw Child object, rather than wrapping them in ChildViewModels first. Is there some way to tell XAML to create a view-model for each child object during the binding process? Or does my ParentViewModel need to explicitly expose a bindable collection of ChildViewModels ? Thanks.

Or does my ParentViewModel need to explicitly expose a bindable collection of ChildViewModels?

It should.

Is there some way to tell XAML to create a view-model for each child object during the binding process?

No, the XAML processor cannot create a view model for each child that wraps the actual child element. XAML is a markup language.

You could possibly use a value converter that binds to the child object and returns a child view model object:

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <DataTemplate.Resources>
            <local:ModelToViewModelConverter x:Key="converter" />
        </DataTemplate.Resources>
        <editor:ChildUserControl DataContext="{Binding Path=, Converter={StaticResource converter}}" />
    </DataTemplate>
</ItemsControl.ItemTemplate>

But I would certainly prefer to expose the appropriate types from the ParentViewModel.

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