【发布时间】:2011-12-11 23:33:03
【问题描述】:
看这个例子:
我创建了一个自定义控件,其中包含一个集合作为依赖属性,并使用从绑定中获取值的子项填充集合的项。如果我使用固定值创建子项,一切正常,如果我绑定它们的值,我会得到绑定错误。
这是具有只读依赖属性的用户控件:
public partial class UserControl1 : UserControl
{
private static DependencyPropertyKey TextsPropertyKey = DependencyProperty.RegisterReadOnly("Texts", typeof(ItemCollection), typeof(UserControl1), new FrameworkPropertyMetadata(new ItemCollection()));
public static DependencyProperty TextsProperty = TextsPropertyKey.DependencyProperty;
public ItemCollection Texts
{
get
{
return (ItemCollection)GetValue(TextsProperty);
}
set
{
SetValue(TextsProperty, value);
}
}
public UserControl1()
{
ItemCollection texts = new ItemCollection();
SetValue(TextsPropertyKey, texts);
InitializeComponent();
}
}
这是窗口 XAML:
<Window x:Class="ControlList.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ControlList="clr-namespace:ControlList"
Title="Window1" Height="300" Width="300">
<Grid>
<ControlList:UserControl1>
<ControlList:UserControl1.Texts>
<ControlList:ItemOfTheList Text="{Binding Text1}"></ControlList:ItemOfTheList>
<ControlList:ItemOfTheList Text="{Binding Text2}"></ControlList:ItemOfTheList>
</ControlList:UserControl1.Texts>
</ControlList:UserControl1>
</Grid>
</Window>
ItemOfTheList 类只是一个具有字符串依赖属性的对象:
public class ItemOfTheList : DependencyObject
{
public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(ItemOfTheList));
public string Text
{
get
{
return (string)GetValue(TextProperty);
}
set
{
SetValue(TextProperty, value);
}
}
public override string ToString()
{
return this.Text;
}
}
并且项目集合只是一个非通用的 FreezableCollection:
public class ItemCollection : FreezableCollection<ItemOfTheList>
{
}
这样我得到以下错误:
System.Windows.Data 错误:2:找不到管理 FrameworkElement 或 FrameworkContentElement 为目标元素。 绑定表达式:路径=文本 1;数据项=空;目标元素是 'ItemOfTheList' (HashCode=52697953);目标属性是“文本”(类型 'String') System.Windows.Data 错误:2:找不到管理 目标元素的 FrameworkElement 或 FrameworkContentElement。 绑定表达式:路径=文本2;数据项=空;目标元素是 'ItemOfTheList' (HashCode=22597652);目标属性是“文本”(类型 '字符串')
如果我将 ItemOfTheList 更改为 FrameworkElement,我总是会在输出窗口中看到 DataContext 为空。如何继承ItemOfTheList 对象中UserControl 的数据上下文?
【问题讨论】:
标签: c# wpf binding collections