Search code examples
c#wpfxamldatacontext

Correctly setting my DataContext in XAML


I know there are similar questions but I am getting this wrong.

I have:

<Window.Resources>
    <local:StudentList x:Key="StudentList" />
    <local:InverseBooleanConverter x:Key="InverseBooleanConverter" />
    <local:StudentAssignmentToStudentAssignmentLookup x:Key="LookupHistoryConvertor" />
    <CollectionViewSource x:Key="cvsStudentList" Source="{StaticResource StudentList}" Filter="CollectionViewSource_Filter"/>

</Window.Resources>

<Window.DataContext>
    <local:OCLMEditorModel/>
</Window.DataContext>

Futher down in my markup I have a DataGrid:

<DataGrid Name="gridStudents" ItemsSource="{Binding Source={StaticResource cvsStudentList}}"
          Margin="2"
          Height="250"
          AutoGenerateColumns="False" IsReadOnly="True">

But I don't think it is right anymore. My OCLMEditorModel object has a public property called StudentList. If I am understanding this right, at the moment my window is associated with an instance of OCLMEditorModel. But the subsequent DataGrid is associated with a distinct instance of the CollectionViewSource.

So I am getting myself confused. Thanks for guidance.


Solution

  • Trying changing your

    <CollectionViewSource x:Key="cvsStudentList" Source="{StaticResource StudentList}" Filter="CollectionViewSource_Filter"/>
    

    to

    <CollectionViewSource x:Key="cvsStudentList" Source="{Binding StudentList}" Filter="CollectionViewSource_Filter"/>
    

    You're correct that your DataContext is set initially to an instance of OCLMEditorModel when the window is instantiated. That should mean that your CollectionViewSource resource should be able to grab the StudentList property from the Window's DataContext through a direct binding.

    Yes, what you're doing in your xaml is binding your DataGrid's ItemsSource to a distinct instance of the CollectionViewSource. However, you're also binding that CollectionViewSource instance to a distinct instance of a StudentList defined in your Window.Resources ( <local:StudentList x:Key="StudentList" /> ), which I don't think is what you want. The change I suggested above will make your CollectionViewSource bind to the OCLMEditorModel's StudentList property instead.