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.
DataContext = thisin a UserControl, because it breaks Bindings to properties of an inherited DataContext. - ClemensDependencyProperty.Register("AncestorContainer", ...)orDependencyProperty.Register(nameof(AncestorContainer), ...)- Clemens