[英]WPF User control binding UIElement
我创建了我的用户控件,希望在此位置绑定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对象DependencyObject的属性中设置“绑定”。
您在编写时有一个错字声明依赖项属性
DependencyProperty.Register("AncestorContainerProperty", ...
应该替换为
DependencyProperty.Register("AncestorContainer", ...
或更好
DependencyProperty.Register(nameof(AncestorContainer), ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.