c# - 如何在 WPF MVVM 中使用嵌套 View

标签 c# wpf mvvm

您好,我正在尝试了解使用嵌套 View 的最佳实践。

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

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

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

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

能否请您告诉我执行此操作的最佳做​​法?

-- 编辑请找到我的 AttributeView(这是 subview 的 xaml 代码)。数据模板绑定(bind)到 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>

最佳答案

根据您的评论,您的父/子关系未反射(reflect)在您的 View 模型中,您有两个选择:

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

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

关于c# - 如何在 WPF MVVM 中使用嵌套 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6198646/

相关文章:

c# - 为什么 ArgumentNullException 和 ArgumentException 的构造函数中的参数是相反的?

wpf - 使用 wpflocalizeextension 改变文化

wpf - Prism、Regions、Magic strings 和重构 : am I missing something here?

c# - .NET 中的 TextFieldParser 等效项?

c# - DataGridView 上的 IOException 写入文本文件 C#

c# - WPF 遍历数据网格

wpf - 如何为 bool[] 中的值实现 INotifyPropertyChanged 功能?

c# - 如何在其父级的ViewModel和Model的集合中删除ViewModel和Model

c# - 绑定(bind) UserControl 的数据上下文

c# - 在 Visual Studio 2013 中导航到定义 "behind"代理