【问题标题】:How to display certain column from a separate table in WPF DataGrid?如何从 WPF DataGrid 中的单独表中显示某些列?
【发布时间】:2019-03-14 00:32:41
【问题描述】:

我有两张桌子,我们称它们为 T 和 V。

表 T 包含需要在数据网格中显示的所有数据,表 V 包含有关表 T 中某个列的数据。因此表 T 包含表 V 的外键。

我想根据表T中的键显示表V中的文本列。

通过使用

myDataGrid.ItemSource = List<T> myTableTList 

<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>

所以 dataStatusKey 是表 V 中的外键,但我想显示表 V 中对应于 dataStatusKey 的文本字段。

如果我用 T 类型的数据填充我的 DataGrid,我该怎么做?

我是否应该创建单独的类并用适当的字段填充它并列出它,然后将我的网格的 ItemSource 设置为这个新的数据类型列表?

【问题讨论】:

    标签: c# wpf entity-framework-4 wpfdatagrid


    【解决方案1】:

    我是否应该创建单独的类并用适当的字段填充它并列出它,然后将我的网格的 ItemSource 设置为这个新的数据类型列表?

    是的。你基本上会这样做:

    • 创建一个新类X,并为您要在DataGrid 中显示的每列添加一个属性
    • 使用从视图模型中的 TV 对象获得的数据填充它
    • ItemsSource 属性绑定到视图模型的IEnumerable&lt;X&gt; 属性

    注意如果T有导航属性,可以直接绑定到这个:

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

    【讨论】:

    • 我正在使用我的新普通类,它只包含在我的 DataGrid 中显示的必要字段。当我尝试 {Binding Path=MyTableName.FieldName} 时,它会根据获取的数据显示适当的字段/文本,这在没有帮助程序类的情况下完美地解决了我的问题。 :) 谢谢。
    猜你喜欢
    • 2015-09-18
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 2010-09-17
    相关资源
    最近更新 更多