简体   繁体   中英

How to display certain column from a separate table in WPF DataGrid?

I have a two tables, lets call them T and V.

Table T contains all the data needed to display in the data grid and table V contains data about certain column in table T. So table T contains a foreign key from table V.

I want to display the text column from table V according to the key in table T.

By using

myDataGrid.ItemSource = List<T> myTableTList 

and

<DataGrid Grid.Row="0" 
    Name="datesDG" 
    Margin="5, 5, 5, 5"  
    SelectionMode="Extended" 
    IsReadOnly="True" 
    AutoGenerateColumns="False" 
    ItemsSource="{Binding dates, Mode=TwoWay}">

    <DataGrid.Columns>
        <DataGridTextColumn Header="Key Column" Binding="{Binding Path=DateKey}" />
        <DataGridTextColumn Header="Publish Date" Binding="{Binding Path=publishDate, StringFormat=\{0:dd.MM.yyyy\}}" />
        <DataGridTextColumn Header="Editing Date" Binding="{Binding Path=editingDate, StringFormat=\{0:dd.MM.yyyy\}}"/>
        <DataGridTextColumn Header="Data Status" Binding="{Binding Path=dataStatusKey}"/>
    </DataGrid.Columns>

</DataGrid>

So dataStatusKey is the foreign key from table V, but I want to display textual field from the table V which corresponds to dataStatusKey.

How can I do that if I fill my DataGrid with data of type T?

Should I create separate class and fill it up with appropriate fields and make a list of it and then set my grid's ItemSource to this new data type list?

Should I create separate class and fill it up with appropriate fields and make a list of it and then set my grid's ItemSource to this new data type list?

Yes. You would basically do this:

  • Create a new class X with a property per column you want to display in the DataGrid
  • Populate it with the data that you get from your T and V objects in your view model
  • Bind the ItemsSource property to an IEnumerable<X> property of the view model

Note that if T has a navigation property, you can bind directly to this one:

<DataGridTextColumn Header="Text" Binding="{Binding Path=V.Text}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM