c# - WPF DataGrid -> 为 CellEditingTemplate 显示的图标

标签 c# wpf templates datagrid wpfdatagrid

当您在 CellEditingTemplate 中使用组合框时,下拉箭头会显示在单元格的右侧。当您使用日期选择器时,单元格右侧会显示一个小日历。

在创建 CellEditingTemplate 时,您如何控制此区域中显示的内容?如果您使用自定义控件并希望在此区域显示图标,该怎么做?

最佳答案

您应该在自定义用户控件中添加此图标。

例子:

假设我们有一个简单的类 Person:

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

我们想创建自定义控件来编辑人名。

1) 我们必须将图标作为资源添加到我们的应用程序 (Build Action = Resource)。

在我的示例中,我创建了文件夹 Images 并将图标“user.png”放在那里。

enter image description here

2) 在下一步中我们创建自定义控件“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) 现在我们可以在 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>

结果:

enter image description here

关于c# - WPF DataGrid -> 为 CellEditingTemplate 显示的图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17910371/

相关文章:

.net - 需要创建一个具有标题和滚动条支持的上下文菜单

c++ - 如果我创建一个模板类,那么我向该类发送引用(指针)的其他类必须被模板化吗?

C++函数映射实现

C++模板类编译错误

c# - 如何在不造成困惑的情况下引用多个类?

c# - Azure Functions 无法再创建 .NET Framework 运行时

wpf - 如何将嵌入的图像资源分配给 XAML 中的图像控件

c# - WPF 中标签上的类似滚动条的动画

c# - 如何将 MVVM 与 CRUD 操作一起使用?

c# - SqlError.Number 说明