我正在尝试使用依赖项属性实现usercontrol。这是我的问题;我想设置一个依赖属性与布局子或我的用户控件的子项。是否有可能,怎么做?
<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>
答案 0 :(得分:12)
是的,在ContentControl
的XAML中声明UserControl
将其Content
属性绑定到DependencyProperty
代码隐藏的UserControl
。
在UserControl类的顶部添加属性:[ContentProperty("Name_Of_Your_Dependency_Property")]
。
然后你可以像你在问题中那样做。该属性定义了默认的依赖属性,因此您不必指定<custom:myControl1.MyDP>
。
类似的东西:
[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>