NRaf
NRaf

Reputation: 7549

WPF - Data template for objects in a datagrid

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

Upvotes: 1

Views: 1789

Answers (1)

Mohammed A. Fadil
Mohammed A. Fadil

Reputation: 9377

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>

Upvotes: 1

Related Questions