運行以下示例,您會看到爲什麼它不起作用。
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;
}
}
}
由於運行時,選擇「新」行,你可以看到導致的警戒值被設置爲在選定項目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 (value != null && string.Equals("{NewItemPlaceholder}", value.ToString(), StringComparison.Ordinal))
{
return null;
}
return value;
}
}
}
正如你可以看到,這是一個不幸的必要性,以測試對定點的ToString()
價值,因爲它是一個內部的類型。您可以選擇(或另外)檢查GetType().Name
是否爲NamedObject
。
5年後,但不妨將它放在這裏:您可以將它與CollectionView.NewItemPlaceholder進行比較,它與您正在做的事情相同,無需在代碼中刻錄「{NewItemPlaceholder}」字符串。 – 2017-03-24 22:27:03