开发者

WPF - Data template for objects in a datagrid

开发者 https://www.devze.com 2023-02-21 19:37 出处:网络
I\'m having trouble finding anything on the subject. Let\'s say I have a list of type Car. Each car object has a range of properties (i.e. make, model, condition, price, owner, etc). I want to display

I'm having trouble finding anything on the subject. Let's say I have a list of type Car. Each car object has a range of properties (i.e. make, model, condition, price, owner, etc). I want to display the list of Cars in a DataGrid but I want control over which properties to display (for example, I may not want to display the owner name in the list or I may want to color the row of a car based on the price of the car).

How can I go about creating a data template开发者_高级运维 to achieve this (just a basic example is needed)?


In order to show and hide the DataGrid columns, you need to bind the visibility of each column to a Boolean property that determines whether to show this column or not. regarding the row background color you can add a DataGrid row style that binds the row Background property to the car price using a value converter that converts the car price to the relevant row color brush. See the following proof of concept:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号