0
votes

I am designing a UserControl that contains a datagrid. The datagrid is not displaying any rows despite my best efforts to bind it to the ItemsSource.

Here is the basic flow of the binding:

  1. A window that contains the UserControl.
  2. The window viewmodel contains an instance of the viewmodel designed for the user control.
  3. I bind the UserControl's ViewModel to this viewmodel via dependency property.
  4. The datagrid is then binded to the observable collection inside the view model, but nothing is showing.

Code (Xaml and VB.Net):

The window view model, binded to all window controls:

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

Window Xaml:

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

User Control code:

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

User control xaml, datagrid binding:

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

It seems a lot of steps, but to my knowledge this is the correct MVVM way to snake the binding to the DataGrid. So far, nothing.

1
Is it VB.NET code?ViVi
yes vb.net will edit questionTekito
Good that you solved it by yourself.ViVi

1 Answers

0
votes

Looks like I might have solved it. The DataGrid's DataContext needed to be pointed at the UserControl.

Just a simple oversight:

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