>我用WPF和MVVM开发了一个应用程序。在其中,我有一个带有DataGrid的窗口。它的 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。
我以为我只设置了项目源的数据上下文,但不是我不确定我是否做错了,或者它是否是某种问题。
提前谢谢。
我不太确定你在期待什么?从您的命名标准来看,您有一个DataGridItemViewModel
表明您希望将视图模型上下文应用于每个数据网格项?
应用于整个视图,然后在该视图模型上具有一个属性,例如ObservableCollection
,它是网格项的集合。然后,将DataGrid
的ItemsSource
设置为绑定到该集合属性。
ItemsSource="{Binding MyItems}"
您通常不需要直接设置网格的数据上下文,它将使用视图的数据上下文(在本例中为Window
)。