如何在另一个UserControl中绑定UserControl?

时间:2016-04-25 12:07:50

标签: c# wpf xaml user-controls

问题是下面的代码应该将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。绑定有问题。

1 个答案:

答案 0 :(得分:0)

我解决了我的问题,这是愚蠢的。 SimpleUserControl中缺少宽度和高度。元素显示但没有宽度和高度。