如何在WPF MVVM中使用嵌套视图

时间:2011-06-01 09:00:20

标签: c# wpf mvvm

您好我正在尝试了解使用嵌套视图的最佳做法。

我有一个'Attribute'视图,它绑定到视图模型中名称值对的集合。我需要在我的UI中的各个地方重用它。

我有另一个'Condition View',它有一个字符串属性和Dictionary(字符串,字符串)集合。我尝试创建一个文本框并在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的bound属性绑定到父视图模型的Dictionary(string,string)的collection属性。什么是最好的方法。我无法将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>

1 个答案:

答案 0 :(得分:4)

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

  1. 在视图模型中创建关系以反映视图中的关系,允许您从父级导航到子级,反之亦然(如果需要)。
  2. 使用RelativeSource FindAncestor绑定向上导航可视化树,找到绑定到父视图模型的控件,并绑定到此控件DataContext
  3. 选项(2)会让你看起来很聪明,但选项(1)会更简单!