【问题标题】:How to bind UserControl inside another UserControl?如何将 UserControl 绑定到另一个 UserControl 中?
【发布时间】:2016-04-25 12:07:49
【问题描述】:

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

【问题讨论】:

  • 我应该能够更改模态初始化的内容,这就是我将 UserControl 传递给模态构造函数的原因。
  • 没有名为self的元素,您可能忘记在Modal的XAML中分配x:Name="self"。您应该已经在 Visual Studio 的“输出”窗口中看到了绑定错误消息。

标签: c# wpf xaml user-controls


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 2022-12-11
    • 2014-03-15
    • 1970-01-01
    • 2011-03-26
    相关资源
    最近更新 更多