【问题标题】:How to use Nested Views in WPF MVVM如何在 WPF MVVM 中使用嵌套视图
【发布时间】:2011-06-01 09:00:19
【问题描述】:

您好,我想了解使用嵌套视图的最佳做法。

我有一个“属性”视图,它绑定到视图模型中的名称值对集合。我需要在 UI 的不同位置重复使用它。

我有另一个“条件视图”,它有一个字符串属性和 Dictionary(string,string) 集合。我尝试创建一个文本框并在 XAML 中添加属性视图控件

    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Content="{x:Static l:StringResources.ConditionViewLabelText}" />
            <TextBox Text="{Binding Type,Mode=TwoWay}" Width="100" />
        </StackPanel>
        <vw:AttributeView />
    </StackPanel>

我想将 AttributeView 的绑定属性绑定到父视图模型的 Dictionary(string,string) 的集合属性。最好的方法是什么。我无法将 vw:AttributeView 绑定到 ConditionViewModels ?

您能告诉我这样做的最佳做法吗?

-- 编辑请找到我的 AttributeView(这是子视图的 xaml 代码)。数据模板绑定到 AttributeViewModel 上的可观察集合

 <StackPanel>
        <ItemsControl ItemsSource="{Binding AllAttributes}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBox Width="100" Text="{Binding Name, Mode=TwoWay}" Margin="5,0,5,0" />
                        <TextBox Width="100" Text="{Binding Value, Mode=TwoWay}" Margin="5,0,5,0" />
                        <TextBlock Width="100" Text="{Binding KeyValue, Mode=OneWay}" />
                        <Button Width="50" Content="{x:Static l:StringResources.AttributeViewButtonDeleteText}" Command="{Binding Path=DataContext.DeleteAttribute, ElementName=AttributeControl}" CommandParameter="{Binding Name}"></Button>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        <Button Name="btnSomething" Content="{x:Static l:StringResources.AttributeViewButtonAddText}" Command="{Binding AddNewAttribute}" />
    </StackPanel>
</Grid>

【问题讨论】:

  • 您需要在这里提供更多信息,能否请您展示一下您的 ViewModel 代码,尤其是两个视图模型之间的关系。
  • 嗨 ColinE(感谢您的回复),我的两个 ViewModel 目前根本不相关。 View 层次结构是否也应该在 ViewModel 级别中复制。正如在父视图的视图模型中应该具有子视图的视图模型类型的公共属性。
  • 嘿,我的问题有一个答案,但它被删除了。奇怪:(

标签: c# wpf mvvm


【解决方案1】:

根据您的 cmets,您的父/子关系未反映在您的视图模型中,您有两种选择:

  1. 在视图模型中创建关系以反映视图中的关系,允许您在需要时从父级导航到子级,反之亦然。
  2. 使用RelativeSource FindAncestor 绑定向上导航可视化树并找到绑定到父视图模型的控件,与此控件绑定DataContext

选项(2)会让你看起来很聪明,但选项(1)要简单得多!

【讨论】:

  • 谢谢ColinE,我会尝试第一种方法,如果它有效或无效,我会回复!
  • 嗨 ColinE,为了实现 Option1,我是否应该将 vw:AttributeView 放在 Item 模板中并将此 ItemTemplate 的 Data 上下文设置为子 Viewmodel 属性?这是否是实现您所说的选项1的正确方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-20
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多