Killnine
Killnine

Reputation: 5900

Converting DataGrid value from int Id to string Description

I have a DataGrid with a column defined like below:

<DataGrid ItemsSource="{Binding Events}" SelectionMode="Single" SelectionUnit="FullRow">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Unit" Width="Auto" Binding="{Binding UnitId}"/>
        ...
    </DataGrid.Columns>
</DataGrid>

The problem is: I am bound to a list of Events that only have a UnitId property. I don't want to display the UnitId. I'd like to display the Description of the Unit.My ViewModel contains an IList<Unit> that looks like the following:

public class Unit 
{
    public int UnitId {get;set;}
    public string Description { get;set;}
}

But the ViewModel is not the datacontext of the DataGrid, so I'd have to do some RelativeSource shenanigans.

So, for instance, if I had a Unit with a UnitId of 1 and a Description of "Upper Folder", I'd want the cell to display "Upper Folder"

I think I may be able to use an IValueConverter for something like this but am not sure if this is the easiest way to go about it.

Upvotes: 1

Views: 1262

Answers (1)

Jonathon Lee
Jonathon Lee

Reputation: 211

  1. Add a property of type 'Unit' to your Event class.

Example:

public class Event
{
    // Other properties...

    //Replace UnitId property with this property
    public Unit Unit {get;set;}

}
  1. Bind to the Description property of the Unit class.

Example: <DataGridTextColumn Header="Unit" Width="Auto" Binding="{Binding Unit.Description}"/>

Upvotes: 2

Related Questions