如何实现内部内容依赖属性?

cem*_*ver 2 wpf dependency-properties

我正在尝试使用依赖项属性实现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>
Run Code Online (Sandbox Code Playgroud)

Lou*_*ann 13

是的,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>
Run Code Online (Sandbox Code Playgroud)