c# - 绑定(bind)到 XAML 中的子 ViewModel 集合

标签 c# wpf xaml mvvm data-binding

我有一个看起来像这样的域模型:

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

我创建了一个自定义 ChildUserControl通过 ChildViewModel 绑定(bind)到 child .我的主窗口绑定(bind)到 ParentViewModel并包含 WrapPanel显示一个 ChildUserControl对于该 parent 拥有的每个 child 。

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

问题在于它设置了 DataContext每个 ChildUserControl到原始 Child对象,而不是将它们包装在 ChildViewModels 中第一的。有没有办法告诉 XAML 在绑定(bind)过程中为每个子对象创建一个 View 模型?或者我的ParentViewModel需要显式公开 ChildViewModels 的可绑定(bind)集合?谢谢。

最佳答案

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



它应该。

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



不,XAML 处理器无法为包装实际子元素的每个子元素创建 View 模型。 XAML 是一种标记语言。

您可以使用 value converter绑定(bind)到子对象并返回 subview 模型对象:
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <DataTemplate.Resources>
            <local:ModelToViewModelConverter x:Key="converter" />
        </DataTemplate.Resources>
        <editor:ChildUserControl DataContext="{Binding Path=, Converter={StaticResource converter}}" />
    </DataTemplate>
</ItemsControl.ItemTemplate>

但我当然更愿意从 ParentViewModel 公开适当的类型。

关于c# - 绑定(bind)到 XAML 中的子 ViewModel 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52030400/

相关文章:

c# - WPF MVVM 更改模型

c# - 使用单例模式 Linq to Sql 数据上下文

wpf - 检测触摸键盘何时在 WPF 中打开

c# - 可以 (a==1 && a==2 && a==3) 在没有多线程的情况下在 C# 中评估为 true 吗?

c# - 从 sqlite 数据库中选择数据并将值绑定(bind)到 Windows Phone 8 应用程序中的列表框项目

c# - 销毁控件

c# - 为什么我不能在我的 WPF 数据网格中选择单元格?

c# - 使用带有 XAML 绑定(bind)的 StringFormat 将文件夹注入(inject)图像路径

c# - 使用依赖注入(inject)进行硬件抽象

c# - 如何获取 MessageBox 按钮标题?