实际上,您可以在ValueConverters 的帮助下做到这一点。当CanUserAddRows=True 行的DataContext 绑定到ItemsSource 的元素或{DataGrid.NewItemPlaceholder} 的空白行。
<DataGrid ItemsSource="{Binding Path=Collection}" CanUserAddRows=True >
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock
Text="{Binding Converter={StaticResource ShowSuitablePart}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
这是ShowSuitablePart转换器的代码。
public class ShowSuitablePart : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value.ToString() == "{DataGrid.NewItemPlaceholder}")
return "This is blank row, just click me to create a new one";
else
((YourCollectionObject)value).SomeProperty;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new Exception();
}
}
如果您需要TwoWay 绑定,则必须在DataTemplate 中使用2 个元素。一个用于空白行,第二个用于具有TwoWay 绑定的常规行。设置可见性绑定以隐藏常规行的第一个元素和空白行的第二个元素。
请记住,如果您确定集合对象的某些属性的路径,它不会在空白行情况下引发 ValueConverter。