WPF用户控件绑定UIElement

时间:2017-10-22 14:32:13

标签: c# wpf xaml

我已经创建了用户控件,我希望能够绑定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>

例外:

  

“Binding”不能在“ParentContainer”类型“TextArea”中设置。   “绑定”只能在DependencyProperty的属性中设置   object DependencyObject。

1 个答案:

答案 0 :(得分:0)

你写了一个拼写错误声明依赖属性

DependencyProperty.Register("AncestorContainerProperty", ... 

应替换为

DependencyProperty.Register("AncestorContainer", ...

或更好

DependencyProperty.Register(nameof(AncestorContainer), ...
相关问题