c# - 如何直接绑定(bind)到 subview 模型?

标签 c# wpf xaml mvvm

目标是直接访问子 ViewModel 中的属性,而不会丢失整个 ViewModel 结构的上下文。

目前,我在字典中有一个资源,其中包含对我用作整个应用程序的数据上下文的 ViewModel 的引用。

因此,我的每个 View 的数据上下文如下所示:

DataContext="{StaticResource mainViewModel}"

在我的 ViewModel 中,我嵌套了子 ViewModel,如下所示:

public class ParentViewModel {
    public ChildVM ChildVM { get; set; }
    public ParentVM(){
        ChildVM = new ChildViewModel();
    }
}

public class ChildViewModel {
    public string SomeProperty { get; set; }
}

在我看来,我可以像这样访问数据上下文中的属性:

<Button Text="{Binding ChildVM.SomeProperty}"/>

但这会变得非常重复。我希望能够做到:

<Button Text="{Binding SomeProperty}"/>

将我的数据上下文设置为类似这样的伪:

DataContext="{StaticResource MainViewModel, Path=ParentVM.ChildVM}"

有什么想法吗?

最佳答案

您可以更改控件组的DataContext

<!-- DataContext is ParentViewModel -->
<Grid>
   <!-- change DataContext to ChildViewModel -->
   <Grid DataContext="{Binding Path=ChildVM}">
      <Button Content="{Binding SomeProperty}"/>
      <Button Content="{Binding AnotherChildProperty}"/>
   </Grid>
</Grid>

关于c# - 如何直接绑定(bind)到 subview 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21608581/

相关文章:

c# - WPF MVVM textBox 文本绑定(bind)

wpf - 我们如何将文本写入 WPF 组合框?

.net - 从 DataTemplate 访问父 DataContext

c# - 如何将列号(例如 127)转换为 Excel 列(例如 AA)

c# - 数据绑定(bind)似乎没有刷新

c# - 在 for 循环中使用 INSERT 语句仅接受第一条记录

C# 类可在 xaml 和代码中绑定(bind)常量

c# - 如何在 XAML 中设置 DataGrid 左上角的样式?

c# - 常见事件处理的最佳实践

c# - C# 和 SQL Server 中的 DateTimeOffset 解析