我已经创建了我的用户控件,我希望能够绑定一个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#中创建我的C#时,它运行得很好--没有这样的例外:
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”中设置“绑定”。“绑定”只能在DependencyProperty对象DependencyObject的属性中设置。
发布于 2017-10-22 17:22:33
在编写时,有一个错误声明依赖项属性。
DependencyProperty.Register("AncestorContainerProperty", ... 它应该被
DependencyProperty.Register("AncestorContainer", ...或者更好
DependencyProperty.Register(nameof(AncestorContainer), ...https://stackoverflow.com/questions/46875262
复制相似问题