【问题标题】:WPF - Data template for objects in a datagridWPF - 数据网格中对象的数据模板
【发布时间】:2011-04-02 08:57:18
【问题描述】:

我无法找到有关该主题的任何内容。假设我有一个 Car 类型的列表。每个汽车对象都有一系列属性(即品牌、型号、状况、价格、所有者等)。我想在 DataGrid 中显示汽车列表,但我想控制要显示的属性(例如,我可能不想在列表中显示车主姓名,或者我可能想根据汽车的价格)。

如何创建数据模板来实现这一点(只需要一个基本示例)?

【问题讨论】:

    标签: wpf datagrid datatemplate


    【解决方案1】:

    为了显示和隐藏 DataGrid 列,您需要将每列的可见性绑定到确定是否显示此列的布尔属性。关于行背景颜色,您可以使用将汽车价格转换为相关行颜色画笔的值转换器添加将行背景属性绑定到汽车价格的 DataGrid 行样式。请参阅以下概念证明:

    <Window x:Class="MyProject.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:System="clr-namespace:System;assembly=mscorlib" 
        Title="MainWindow"
        Height="136" Width="525">
    <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
        <DataGrid.RowStyle>
            <Style TargetType="{x:Type DataGridRow}">
                <Setter Property="Background"
                        Value="{Binding SomeProperty,
                            Converter={StaticResource SomePropertyToBrushConverter}}"/>
            </Style>
        </DataGrid.RowStyle>
    
        <DataGrid.Columns>
            <DataGridTextColumn Header="Owner Name"
                                Visibility="{Binding IsOwnerNameVisible,
                                    Converter={StaticResource BooleanToVisiblityConverter}}"/>
        </DataGrid.Columns>
    </DataGrid>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      相关资源
      最近更新 更多