wpfxamlinfragisticslegacy-codexamdatagrid

WPF Binding to parent object in an XamDataGrid


I have inherited a legacy project that uses WPF. We make use of Infragistics.

Below is a made-up class structure:

public class DogsVM
{
    public string ViewName { get; set; } = "My Dogs";
    public List<Dog> Dogs { get; set; }
}

public class Dog
{
    public string DogName { get; set; }
    public string Description { get; set; }
}

I am using a XamDataGrid to display my data.

Currently the DataSource on the XamDataGrid is DataSource="{Binding CollectionView}".

When I output the field I am using the following

<igDP:Field Name="DogName " Label="Dog Name" AllowEdit="False" />

I want the change the Label to be from DogsVM and select the field ViewName

If I do

<igDP:Field Name="DogName " Label="{Binding ViewName}" AllowEdit="False" />

DogName is outputted as I am looking at a Dog object, not a DogsVM object. How can I get to the parent object in the label binding?


Solution

  • On the Infragistics site there is the following explanation for a similar problem:

    Fields in the XamDataGrid are not visual elements in WPF, and as such cannot be bound directly to a data context, as they do not expose one inherited from FrameworkElement.

    In order to bind the properties of the non-visual elements of the XamDataGrid such as Field, FieldSettings, or FieldLayoutSettings, I would recommend using a FieldBinding. You can read about FieldBinding in the XamDataGrid here: https://www.infragistics.com/help/wpf/xamdatagrid-binding-field-fieldlayout-to-mvvm.

    So, on the Infragistics site is recommended to use FieldBinding markup extension in order to bind properties to the Field, FieldSettings, or FieldLayoutSettings.
    While mentioned post includes example that uses the MVVM pattern the FieldBinding markup extension can be used without it.

    Related to the question above consider to set the DataContext in the constructor:

    public YouWindowConstructor()
    {        
        InitializeComponent();
        DataContext = new DogsVM();
    }
    

    Now set DataSource for the XamDataGrid and use the FieldBinding markup extension:

    
    <igDP:XamDataGrid DataSource="{Binding Path=Dogs}" AutoFit="True">
        <igDP:XamDataGrid.FieldLayoutSettings>            
            ...
            <igDP:XamDataGrid.FieldLayouts>
                <igDP:FieldLayout>
                    <igDP:FieldLayout.Fields>    
                        ...
                        <igDP:Field Name="DogName" Label="{igDP:FieldBinding ViewName}" AllowEdit="False" />   
                        ...              
                    </igDP:FieldLayout.Fields>
                </igDP:FieldLayout>
            </igDP:XamDataGrid.FieldLayouts>
    </igDP:XamDataGrid>        
        
    

    See similar: https://stackoverflow.com/a/64545966/6630084