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

9udxz4iz  于 2023-05-19  发布在  其他
关注(0)|答案(2)|浏览(137)

我正在尝试实现一个带有依赖属性的用户控件。这是我的问题我想设置一个依赖属性与布局子或我的用户控件的子。这是否可能,如何做到?

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

vybvopom1#

是的,在UserControl的XAML中声明ContentControl
将其Content属性绑定到UserControl的代码隐藏上的DependencyProperty
添加属性:[ContentProperty("Name_Of_Your_Dependency_Property")]在你的UserControl类之上。
然后你可以像你在问题中所做的那样做。该属性定义了默认的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>
mftmpeh8

mftmpeh82#

工作正常。
1.已创建UserControl并添加绑定DP的ContentControl。(如上面的解决方案中所述,在代码后面创建DP。

<UserControl x:Class="WpfTry2.Controls.DummyContentControl"
... x:Name="dummyContent">
   <Grid>
        <ContentControl Content="{Binding InnerContent, ElementName=dummyContent}"/>
   </Grid>
</UserControl>

1.使用Windows中的UserControl

<controls:DummyContentControl>
            <controls:DummyContentControl.InnerContent>
                <Grid Background="Aqua" HorizontalAlignment="Center" VerticalAlignment="Center">
                    <TextBlock Text="InnerContent" FontSize="32"></TextBlock>
                </Grid>
            </controls:DummyContentControl.InnerContent>
</controls:DummyContentControl>

相关问题