无法在 WPF 用户控件中绑定 DataGrid ItemsSource

Cannot bind DataGrid's ItemsSource inside WPF User Control

我正在设计一个包含数据网格的用户控件。尽管我已尽最大努力将数据网格绑定到 ItemsSource.

,但数据网格未显示任何行

绑定的基本流程如下:

  1. 包含 UserControl 的 window。
  2. window 视图模型包含为用户控件设计的视图模型实例。
  3. 我通过依赖关系将 UserControl 的 ViewModel 绑定到此 viewmodel 属性。
  4. 数据网格随后绑定到视图模型中的可观察集合,但没有显示任何内容。

代码(Xaml 和 VB.Net):

window 视图模型,绑定到所有 window 控件:

Public Class WindowVM
    ...
    Public Property UserControlViewModel as New UserControlVM
End Class

Window Xaml:

   <local:MyUserControl ViewModel="{Binding UserControlViewModel, Mode=OneWay}"/>

用户控制代码:

Public Shared ReadOnly ViewModelProperty As DependencyProperty = DependencyProperty.Register("ViewModel", GetType(UserControlVM), GetType(MyUserControl), New PropertyMetadata(Nothing))
...
 Public Property ViewModel As UserControlVM
    Get
        Return CType(Me.GetValue(ViewModelProperty), UserControlVM)
    End Get
    Set(value As UserControlVM)
        Me.SetValue(ViewModelProperty, value)
    End Set
End Property
....
Public Class UserControlVM
    Public Property RunItems As New ObservableCollection(Of RunVM)
End Class

用户控件xaml,数据网格绑定:

<DataGrid DataContext="{Binding ViewModel}"
  ItemsSource="{Binding RunItems}" ...

似乎有很多步骤,但据我所知,这是蛇形绑定到 DataGrid 的正确 MVVM 方法。到目前为止,什么都没有。

看来我可能已经解决了。 DataGridDataContext 需要指向 UserControl

只是一个简单的疏忽:

<DataGrid DataContext="{Binding ViewModel, RelativeSource={RelativeSource AncestorType=UserControl}}" 
ItemsSource="{Binding RunItems}"