Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
3627
Need to pass in DataContext of grid to a converter
posted

Related to another posting... I need to pass the DataContext of the grid into a converter being called for a field in the grid. I've tried the following syntax, and a few others with no luck.

<igDP:Field  Name="SuggestedMasterId" Converter="{StaticResource masterForeignKeyConverter}" ConverterParameter="{Binding Path=DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type igDP:XamDataGrid}} }">
    <igDP:Field.Settings>
        <igDP:FieldSettings EditAsType="{x:Type sys:String}" />
    </igDP:Field.Settings>
</igDP:Field>

Does anyone know how to do this? Admittedly, I find binding syntax a bit mysterious. :(

The reason I need to do this is because the converter needs access to a collection property off the DC that the grid's bound to. The DataSource of the grid is bound to another collection property of the DC, so without the DC the converter has no access to the other properties of the DC.

  • 6867
    Verified Answer
    posted

    A Field is not in the element tree, so you cannot bind its properties to elements in the element tree.  There are solutions, however.  You can use my DataContextSpy class to export the XamDataGrid's DataContext to the Fields. 

    Using the version of DataContextSpy in the aforementioned blog post, you can bind a Field's ConverterParameter like so:

    <igDP:XamDataGrid DataSource="{Binding}">
      <igDP:XamDataGrid.Resources>
        <local:DataContextSpy x:Key="Spy" />
      </igDP:XamDataGrid.Resources>
      <igDP:XamDataGrid.FieldLayouts>
        <igDP:FieldLayout>
          <igDP:FieldLayout.Fields>
            <igDP:Field
              Name="Name"
              Converter="{StaticResource MyConv}"
              ConverterParameter="{Binding Source={StaticResource Spy}, Path=DataContext}"
              />
            <igDP:Field Name="Status" />
          </igDP:FieldLayout.Fields>
        </igDP:FieldLayout>
      </igDP:XamDataGrid.FieldLayouts>
    </igDP:XamDataGrid>

    For a more comprehensive overview of DataContextSpy, and other techniques for creating artificial inheritance contexts, I suggest you read my CodeProject article on that subject here. Note: if you use the version of DataContextSpy presented in that article, you'll need to set its IsSynchronizedWithCurrentItem property to false for it to work the same as the simpler version listed above.