0
votes

I have creted my User Control where I would like to make posibility to bind a UIElement. My user control:

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));
 }

When creating my UserControl in C# it is working fine - no exceptions like this:

var textArea = new TextArea
{
    AncestorContainer = Root, // Root is name of Grid
    Text = textItem.Text
};

However when trying to use binding in XAML I get an exception:

<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>

And the exception:

"Binding" cannot be set in the "ParentContainer" type "TextArea". "Binding" can only be set in the properties of the DependencyProperty object DependencyObject.

1
As a note, you should never set DataContext = this in a UserControl, because it breaks Bindings to properties of an inherited DataContext. - Clemens
That said, your error is in the dependency property declaration. It should be DependencyProperty.Register("AncestorContainer", ...) or DependencyProperty.Register(nameof(AncestorContainer), ...) - Clemens

1 Answers

0
votes

You have a typo declaring dependency property as you have written

DependencyProperty.Register("AncestorContainerProperty", ... 

which should be replaced by

DependencyProperty.Register("AncestorContainer", ...

or better

DependencyProperty.Register(nameof(AncestorContainer), ...