运行下面的示例,你会看到为什么它不起作用。
XAML:
<Window x:Class="DataGridTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<TextBlock DockPanel.Dock="Bottom" Text="{Binding SelectedItem, ElementName=dataGrid}"/>
<TextBlock DockPanel.Dock="Bottom" Text="{Binding SelectedItem}"/>
<DataGrid x:Name="dataGrid" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" CanUserAddRows="True" CanUserDeleteRows="True" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
<DataGridTextColumn Header="Last Name" Binding="{Binding FirstName}"/>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</Window>
代码后台:
namespace DataGridTest
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
public partial class MainWindow : Window, INotifyPropertyChanged
{
private readonly ICollection<Person> items;
private Person selectedItem;
public MainWindow()
{
InitializeComponent();
this.items = new ObservableCollection<Person>();
this.items.Add(new Person
{
FirstName = "Kent",
LastName = "Boogaart"
});
this.items.Add(new Person
{
FirstName = "Tempany",
LastName = "Boogaart"
});
this.DataContext = this;
}
public ICollection<Person> Items
{
get { return this.items; }
}
public Person SelectedItem
{
get { return this.selectedItem; }
set
{
this.selectedItem = value;
this.OnPropertyChanged("SelectedItem");
}
}
private void OnPropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class Person
{
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
public override string ToString()
{
return FirstName + " " + LastName;
}
}
}
如您所见,运行时选择“new”行会导致在DataGrid
中设置一个哨兵值作为选定项目。但是,WPF无法将该哨兵项目转换为Person
,因此SelectedItem
绑定无法转换。
要解决这个问题,您可以在绑定上放置一个转换器,检测哨兵并在检测到哨兵时返回null
。以下是一个实现此功能的转换器:
namespace DataGridTest
{
using System;
using System.Windows.Data;
public sealed class SentinelConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (item.Equals(CollectionView.NewItemPlaceholder)))
{
return null;
}
return value;
}
}
}
正如您所看到的,不幸的是必须对哨兵的ToString()
值进行测试,因为它是一个内部类型。您还可以(或者另外)检查GetType().Name
是否为NamedObject
。