jon*_*iba 6 .net c# data-binding collections wpf
我有一个自定义集合,我将其传递给WPF客户端,该客户端将集合绑定到datagrid使用AutoGenerateColumns="True".但是,数据网格显示空行(尽管空行数正确).我究竟做错了什么?以下是一些示例代码.现在我已经省略了所有与之相关的内容INotifyPropertyChanged,INotifyCollectionChanged因为我首先想要在网格中显示一些数据.
我还要提一下,我已尝试实现上述两个接口,但它们似乎与此问题无关.
(您可能实际上不想查看示例代码,因为它没有什么有趣的.集合实现只是包装内部List.)
一些随机的POCO:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
简单的集合实现:
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
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
窗口的代码隐藏:
public MainWindow()
{
InitializeComponent();
MyCollection<Person> persons = new MyCollection<Person>()
{
new Person(){FirstName="john", LastName="smith"},
new Person(){FirstName="foo", LastName="bar"}
};
dataGrid1.DataContext = persons;
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果你改变代码隐藏使用List <Person>而不是MyCollection <Person>,一切都按预期工作.
编辑:
以上代码不是从实际情况中获取的.我只发布它来展示我正在做的事情,以便测试我的问题并使其更容易复制.实际的自定义集合对象非常复杂,我无法在此处发布.同样,我只是想了解需要做的事情背后的基本概念,以便数据网格正确绑定到自定义集合并自动为底层对象生成列.
显然,为了让 AutoGenerateColumns 在 WPF 中工作DataGrid,您的集合必须实现IItemProperties,尽管我发现将我的集合包装在(windows 表单) BindingList 中也能达到目的(它实际上包装了您的集合,ObservableCollection与只需将您的集合的成员复制到其自身中)。