绑定到集合的属性

时间:2014-04-08 02:48:58

标签: c# wpf xaml collections binding

上下文

WPF数据网格允许开发人员手动将每个列绑定到ItemsSource的属性,如下所示:

<DataGrid ItemsSource="{Binding People}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}"/>
        <DataGridTextColumn Binding="{Binding Age}"/>
        <DataGridTextColumn Binding="{Binding Country}"/>
    </DataGrid.Columns>
</DataGrid>

这些列绑定的优点是,如果绑定不与People集合中对象的属性相对应,Visual Studio将显示设计时警告。它还将通过intellisense提供有效属性列表。

我正在开发一种不同类型的网格,但我无法获得此功能。目前我已经开发出类似的东西:

<my:Grid ItemsSource="{Binding People}">
    <my:Column Property="Name" />
    <my:Column Property="Age" />
    <my:Column Property="Country" />
</my:Grid>

在内部,这些基于字符串的属性在运行时通过type.GetProperty()进行查找。

我的问题

如何在DataGrid示例中实现属性绑定?我查看了反编译的DataGrid源代码,发现DataGridBoundColumn.Binding的类型为BindingBase。

我将BindingBase重新绑定到我的自定义网格中,但我仍然没有获得强类型或智能感知选项,可能是因为BindingBase不知道它适用于哪种类型,但我不知道如何提供它它需要的背景。

1 个答案:

答案 0 :(得分:0)

将属性my:Column.Property的实现更改为依赖属性。这将允许您使用Bindings,也许这会有所帮助。但是Binding周围的智能感知更像是VS-XAML设计师而不是你的代码。

//http://msdn.microsoft.com/en-us/library/ms752914(v=vs.110).aspx

public static readonly DependencyProperty PropertyProperty = 
DependencyProperty.Register(
"Property", typeof(Boolean),

);
public bool IsSpinning
{
get { return (bool)GetValue(PropertyProperty ); }
set { SetValue(PropertyProperty , value); }
}