如何将 UserControl 绑定到另一个 UserControl 中?

How to bind UserControl inside another UserControl?

问题是下面应该将 UserControl 传递给 Modal(也是 UserControl)的代码不起作用。看起来很简单,我一定是漏掉了一些小东西。

这是代码

XAML:

<UserControl x:Class="Test.UserControls.Modal"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Grid>
    ....
    <ContentControl Content="{Binding PrimaryElement, ElementName=self}" />
</Grid>

<UserControl x:Class="Test.UserControls.SimpleUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Grid>
     <Label>Test</Label>
</Grid>
</UserControl>

C#:

namespace Test.UserControls
{

    public partial class Modal: UserControl
    {

        public static readonly DependencyProperty PrimaryElementPropery =
        DependencyProperty.Register("PrimaryElement", typeof(UserControl), typeof(Modal), new FrameworkPropertyMetadata
            {
                 BindsTwoWayByDefault = false
             });

        public UserControl PrimaryElement
        {
            get { return (UserControl)GetValue(PrimaryElementPropery); }
            set { SetValue(PrimaryElementPropery, value); }
        }

        public Modal (UserControl userControl)
        {
            // userControl is SimpleUserControl
            PrimaryElement = userControl;
            InitializeComponent();
        }
    }
}

因此,显示了模态,但其中没有 SimpleUserControl。绑定有问题。

我已经解决了我的问题,它很愚蠢。 SimpleUserControl 中缺少宽度和高度。该元素正在显示但没有宽度和高度。