当您在CellEditingTemplate中使用组合框时,单元格右侧会显示一个下拉箭头。当您使用日期选择器时,单元格右侧会显示一个小日历。
创建CellEditingTemplate时,如何控制在此区域中显示的内容?如果您使用自定义控件并想要在此区域中显示图标,应该如何操作?
创建CellEditingTemplate时,如何控制在此区域中显示的内容?如果您使用自定义控件并想要在此区域中显示图标,应该如何操作?
您应该在自定义用户控件中添加此图标。
例如:
假设我们有一个简单的Person类:
class Person
{
public int ID { get; set; }
public string Name { get; set; }
}
我们希望创建一个自定义控件来编辑人名。
1) 我们必须将图标添加到我们的应用程序资源中(Build Action = Resource
)。
在我的示例中,我创建了一个名为Images的文件夹,并在其中放置了图标"user.png"。
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>