Search code examples
c#wpftemplatesdatagridwpfdatagrid

WPF DataGrid -> Icon Shown For CellEditingTemplate


When you use a combo box in the CellEditingTemplate a drop down arrow is shown on the right hand side of the cell. When you use a date picker a small calender is shown on the right hand side of the cell.

When creating a CellEditingTemplate how do you control what is shown in this area? If you use a custom control and want to show a icon in this area how would this be done?


Solution

  • You should add this icon in your custom user control.

    Example:

    Let's say that we have simple class Person:

    class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    

    and we want to create custom control to edit person name.

    1) We must add icon to our app as resource (Build Action = Resource).

    In my example I created folder Images and put there icon "user.png".

    enter image description here

    2) In the next step we create custom control "NameUserControl":

    <UserControl x:Class="WpfApplicationDataGrid.NameUserControl"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 mc:Ignorable="d" 
                 d:DesignHeight="300" d:DesignWidth="300">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="30" />
            </Grid.ColumnDefinitions>      
    
            <TextBox Text="{Binding Path=Name}" />
            <Image Source="/Images/user.png" Grid.Column="1" />
        </Grid>
    </UserControl>
    

    3) Now we can using new custom user control in CellEditingTemplate:

    <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding ID}" />
            <DataGridTemplateColumn Header="Name">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Name}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <local:NameUserControl />
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
    

    Result:

    enter image description here