我试图将带有索引器的类绑定到DataGrid。这是我的班级:
public class Record : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private readonly ConditionalWeakTable<Column, State> state =
new ConditionalWeakTable<Column, State>();
private string name;
public string Name
{
get { return this.name; }
set
{
if (this.name != value)
{
this.name = value;
this.RaisePropertyChanged("Name");
}
}
}
[IndexerName("Item")]
public string this[Column column]
{
get { return state.GetOrCreateValue(column).Value; }
set
{
var cl = state.GetOrCreateValue(column);
if (cl.Value != value)
{
cl.Value = value;
this.RaisePropertyChanged("Item[]");
}
}
}
protected void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(
this,
new PropertyChangedEventArgs(propertyName));
}
}
private class State
{
private string value;
public State()
{
this.value = string.Empty;
}
public string Value
{
get { return this.value; }
set { this.value = value; }
}
}
}
public class Column
{
}
这是xaml
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Width="200" Binding="{Binding Name}" />
<DataGridTextColumn x:Name="FirstColumn" Header="First" Width="200" />
<DataGridTextColumn x:Name="SecondColumn" Header="Second" Width="200" />
</DataGrid.Columns>
</DataGrid>
以下是
背后的代码public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var first = new Column();
var second = new Column();
this.FirstColumn.Binding = new Binding
{
Path = new PropertyPath("[(0)]", first)
};
this.SecondColumn.Binding = new Binding
{
Path = new PropertyPath("[(0)]", second)
};
var record1 = new Record { Name = "test 1" };
record1[first] = "First test 1";
record1[second] = "Second test 1";
var record2 = new Record { Name = "test 2" };
record2[first] = "First test 2";
record2[second] = "Second test 2";
this.DataContext = new ObservableCollection<Record> { record1, record2 };
}
}
代码实际上正在运行。我可以打开窗口,并按预期填充值。但是当我尝试编辑一个单元格时,它会在BindingGroup.CommitEdit()中使用NullReferenceException进行缓存。
我也尝试过与TextBox相同的绑定,它运行得很好。
任何想法如何解决?