Search code examples
wpfxamlentity-framework-6devexpressdxgrid

EF6, Code First. How to set alternative data source for GridControl column using XAML Devexpress


I have two related entities:

public class Event
{
    public string ID { get; set; }
    public DateTime EventDate { get; set; }
    public string EventData { get; set; } 
    public string DocID1 { get; set; }
    public int DocID2 { get; set; }
    public virtual Document Document1 { get; set; }
    public virtual Document Document2 { get; set; }

}

public class Document
{

    public string ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Number { get; set; }

}

Also created List to display data in WPF:

private ObservableCollection<Event> eventList;
public ObservableCollection<Event> EventList
        {
            get { return eventList; }
            set
            {
                if (value != eventList)
                {
                    eventList = value;
                }
                RaisePropertyChanged(nameof(EventList));
            }
        }

data for my EventList is taken from entity Event:

var query = DBContext.Events.Select(x => x).AsQueryable();
EventList = query.ToList();

What I need is how to set GridControl Column "colFirstName" value to be equal "Document1.FirstName" if DocID1 is not null and "Document2.FirstName" if DocID2 is not null. My XAML code for GridControl is below, could You help how to do it in Xaml, not in ViewModel, or if there is no way to do it in Xaml, what is the best way to do it in ViewModel.

<dxg:GridControl AutoPopulateColumns="False"
ItemsSource="{Binding EventList, UpdateSourceTrigger=PropertyChanged}">

                        <dxg:GridControl.Columns>
                            <dxg:GridColumn
                                x:Name="colEventData"
                                Width="120"
                                FieldName="EventData"
                                 Header =" Event data"
                                Visible="True" >
                        </dxg:GridColumn>

                        <dxg:GridColumn
                                x:Name="colFirsnName"
                                Width="120"
                                FieldName="Document1.FirstName"
                                Header="First Name"
                                Visible="True"
                                VisibleIndex="1" />
                          </dxg:GridControl.Columns>
                        </dxg:GridControl>

Solution

  • You can use the UnboundExpression property to create a column with a custom expression. For example, to conditionally show values from different properties, use the Iif function:

    <dxg:GridColumn FieldName="CustomColumn" x:Name="colFirsnName" 
                    UnboundExpression="Iif(IsNullOrEmpty([DocID1]), [Document2.FirstName], [Document1.FirstName])" 
                    UnboundType="String"/>