c# - 在 DataGrid 上设置 DataContext

标签 c# wpf mvvm resharper datacontext

我使用 WPF 和 MVVM 开发了一个应用程序。其中我有一个带有数据网格的窗口。它的 ViewModel 包含一些窗口属性和一个 DataGrid 属性(ObservableCollection<DataGridItemViewModel>)。

在窗口xaml中我以这种方式设置设计DataContext:

<Window x:Class="XXX"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

            mc:Ignorable="d"

            d:DataContext="{d:DesignInstance TheTypeOfTheWindowViewModelHere}">

然后我想以这种方式将设计 DataContext 设置到 DataGrid 上:

<DataGrid ItemsSource="{Binding Path=PropertyOfTheDataGrid}" d:DataContext="{d:DesignInstance DataGridItemViewModel}" >

但随后我收到一条警告,告诉我在 DataGridItemViewModel 中找不到 PropertyOfTheDataGrid。

我以为我只设置了 ItemsSource 的 DataContext,但不是,我不确定我是否做错了或者是否存在某种问题。

提前致谢。

最佳答案

我不太确定你在期待什么?根据您的命名标准,您有一个 DataGridItemViewModel ,这表明您希望将 View 模型上下文应用于每个数据网格项?

通常,您会将一个 View 模型应用于整个 View ,然后在该 View 模型上拥有一个属性,例如 ObservableCollection,它是网格项目的集合。然后,您可以将 DataGridItemsSource 设置为绑定(bind)到该集合属性。

ItemsSource="{Binding MyItems}"

您通常不需要直接设置网格的数据上下文,它会使用 View 的数据上下文(在本例中为 Window)。

关于c# - 在 DataGrid 上设置 DataContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12422505/

相关文章:

c# - WPF 绑定(bind)到自定义 DependencyProperty - IsChecked 有时是相反的属性值

带数据库的 WPF MVVM 示例

c# - 当 MVVM 中的 CaretIndex 更改时我没有收到通知

MVVM 和 VS2010 - 有没有办法指定 tabcontrol 而不在代码隐藏中添加代码

c# - 有条件地设置 GridViewColumn 单元格模板

c# - 位图无法返回?

c# - 检查重叠日期

c# - 在 c# 中根据其子元素对 arraylist 进行排序

c# - 将 c 字符数组 [128] 编码到 c#

wpf - WPF DataGrid计算的总计列