【发布时间】:2017-10-22 14:32:12
【问题描述】:
我已经创建了我想要绑定 UIElement 的用户控件。我的用户控件:
public partial class TextArea : UserControl
{
public UIElement AncestorContainer
{
get => (UIElement)GetValue(AncestorContainerProperty);
set => SetValue(AncestorContainerProperty, value);
}
public TextArea()
{
InitializeComponent();
DataContext = this;
}
public static readonly DependencyProperty AncestorContainerProperty =
DependencyProperty.Register("AncestorContainerProperty", typeof(UIElement), typeof(TextArea), new PropertyMetadata(null));
}
在 C# 中创建我的 UserControl 时,它工作正常 - 没有这样的例外:
var textArea = new TextArea
{
AncestorContainer = Root, // Root is name of Grid
Text = textItem.Text
};
但是,当尝试在 XAML 中使用绑定时,出现异常:
<ItemsControl ItemsSource="{Binding SuggestedTexts}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<components:TextArea
AncestorContainer="{Binding ElementName=Sidebar}"/> <!-- Side bar is name of Grid above in XAML -->
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
还有例外:
不能在“ParentContainer”类型“TextArea”中设置“Binding”。 “绑定”只能在DependencyProperty的属性中设置 对象依赖对象。
【问题讨论】:
-
请注意,您应该永远在 UserControl 中设置
DataContext = this,因为它会破坏对继承 DataContext 属性的绑定。 -
也就是说,您的错误出在依赖属性声明中。应该是
DependencyProperty.Register("AncestorContainer", ...)或DependencyProperty.Register(nameof(AncestorContainer), ...)