【发布时间】:2011-07-11 04:32:36
【问题描述】:
我有一个要传递给 WPF 客户端的自定义集合,该客户端使用AutoGenerateColumns="True" 将集合绑定到datagrid。然而,数据网格显示的是空行(尽管空行的数量是正确的)。我究竟做错了什么?以下是一些示例代码。现在我已经省略了与INotifyPropertyChanged 和INotifyCollectionChanged 相关的所有内容,因为我首先希望在网格中显示一些数据。
我还要提一下,上面两个接口我都试过了,但是好像和这个问题没什么关系。
(您可能实际上不想查看示例代码,因为它绝对没有什么有趣的东西。集合实现只是包装了一个内部列表。)
一些随机的 POCO:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
简单的集合实现:
public class MyCollection<T> : IList<T>
{
private List<T> list = new List<T>();
public MyCollection()
{
}
public MyCollection(IEnumerable<T> collection)
{
list.AddRange(collection);
}
#region ICollection<T> Members
public void Add(T item)
{
list.Add(item);
}
public void Clear()
{
list.Clear();
}
public bool Contains(T item)
{
return list.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
list.CopyTo(array, arrayIndex);
}
public int Count
{
get { return list.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
return list.Remove(item);
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region IList<T> Members
public int IndexOf(T item)
{
return list.IndexOf(item);
}
public void Insert(int index, T item)
{
list.Insert(index, item);
}
public void RemoveAt(int index)
{
list.RemoveAt(index);
}
public T this[int index]
{
get { return list[index]; }
set { list[index] = value; }
}
#endregion
}
XAML:
<Window x:Class="TestWpfCustomCollection.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">
<Grid>
<DataGrid AutoGenerateColumns="True"
HorizontalAlignment="Stretch"
Name="dataGrid1" VerticalAlignment="Stretch"
ItemsSource="{Binding}"
/>
</Grid>
</Window>
窗口的代码隐藏:
public MainWindow()
{
InitializeComponent();
MyCollection<Person> persons = new MyCollection<Person>()
{
new Person(){FirstName="john", LastName="smith"},
new Person(){FirstName="foo", LastName="bar"}
};
dataGrid1.DataContext = persons;
}
顺便说一句,如果您将代码隐藏更改为使用 List
编辑:
以上代码并非取自真实情况。我发布它只是为了展示我在做什么,以测试我的问题并使其更容易复制它。 实际的自定义集合对象非常复杂,我无法在此处发布。同样,我只是想了解为了使数据网格正确绑定到自定义集合并为基础对象自动生成列需要做什么背后的基本概念。
【问题讨论】:
标签: c# .net wpf data-binding collections