您好,我正在尝试了解使用嵌套 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 模型中,您有两个选择:
- 在 View 模型中创建关系以反射(reflect) View 中的关系,允许您在需要时从父级导航到子级,反之亦然。
- 使用 RelativeSource FindAncestor绑定(bind)以向上导航可视化树并找到绑定(bind)到父 View 模型的控件,竞标到此控件
DataContext
。
选项(2)会让你看起来很聪明,但选项(1)要简单得多!
关于c# - 如何在 WPF MVVM 中使用嵌套 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6198646/