[英]How does ItemsControl.ItemsSource bind from something that doesn't implement IEnumerable?
ItemsControl.ItemsSource is IEnumerable
. ItemsControl.ItemsSource是IEnumerable
。 DataTable isn't IEnumerable
. DataTable不是IEnumerable
。 I would expect DataTable
to fail to bind to ItemsSource
.我希望DataTable
无法绑定到ItemsSource
。 Yet, the code below works.然而,下面的代码有效。 Why?为什么?
<DataGrid ItemsSource="{Binding Table}"/>
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public DataTable Table { get; set; } = new DataTable();
When I set ItemsSource
to DataTable
without binding, it fails like I would expect.当我在没有绑定的情况下将ItemsSource
设置为DataTable
,它会像我预期的那样失败。 However, casting DataTable
to IEnumerable<DataRowView>
compiles without error.但是,将DataTable
为IEnumerable<DataRowView>
编译时不会出错。
new DataGrid().ItemsSource = new DataTable(); // Cannot implicitly convert type 'System.Data.DataTable' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?)
new DataGrid().ItemsSource = (IEnumerable<DataRowView>)new DataTable(); // compiles without error
Does binding cast DataTable
to IEnumerable<DataRowView>
?绑定是否将DataTable
为IEnumerable<DataRowView>
? Where is the documentation for this behavior?这种行为的文档在哪里? I would expect the ItemsSource
documentation to explain this casting, but I don't see anything there.我希望ItemsSource
文档能够解释这种转换,但我在那里什么也没看到。
First of all, the cast to IEnumerable<DataRowView>
does not work.首先,转换为IEnumerable<DataRowView>
不起作用。 It compiles, but will throw at runtime:它编译,但会在运行时抛出:
The binding works for DataTable
because it implements IListSource
绑定适用于DataTable
因为它实现了IListSource
This interface is explicitly accounted for in the WPF DefaultValueConverter
此接口在 WPF DefaultValueConverter
明确说明
// special case for converting IListSource to IList
if (typeof(IListSource).IsAssignableFrom(sourceType) &&
targetType.IsAssignableFrom(typeof(IList)))
{
return new ListSourceConverter();
}
And the default converter is created with the binding并且默认转换器是使用绑定创建的
IValueConverter converter = Engine.GetDefaultValueConverter(type, TargetProperty.PropertyType, IsReflective);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.