I'm trying to implement a usercontrol with dependency properties. Here is my question; i want to set a dependency property with layout child or children of my user control. Is it possible and how can it be done?
<custom:myControl1>
<Label>Controls</Label>
<Label>I want</Label>
<Label>to set</Label>
<Label>as the dependency property</Label>
<Button Content="Is it possible?" />
</custom:myControl1>
Yes, declare a ContentControl
in the XAML of your UserControl
.
Make it bind its Content
property to a DependencyProperty
on the code-behind of your UserControl
.
Add the attribute: [ContentProperty("Name_Of_Your_Dependency_Property")]
on top of your UserControl class.
Then you can do precisely as you did in your question. The attribute defines the default Dependency Property so that you dont have to specify <custom:myControl1.MyDP>
.
Something like:
[ContentProperty("InnerContent")]
public class MyControl : UserControl
{
#region InnerContent
public FrameworkElement InnerContent
{
get { return (FrameworkElement)GetValue(InnerContentProperty); }
set { SetValue(InnerContentProperty, value); }
}
// Using a DependencyProperty as the backing store for InnerContent. This enables animation, styling, binding, etc...
public static readonly DependencyProperty InnerContentProperty =
DependencyProperty.Register("InnerContent", typeof(FrameworkElement), typeof(MyControl), new UIPropertyMetadata(null));
#endregion
}
<UserControl ...>
<ContentControl Content="{Binding InnerContent, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
</UserControl>