【问题标题】:Why does my UserControl not display in the designer?为什么我的 UserControl 不显示在设计器中?
【发布时间】:2014-07-23 09:36:57
【问题描述】:

我已经实现了一个用户控件,可以让我快速构建几个类似的界面屏幕。基本上它定义了两个依赖属性MainContentUserInteractions,然后显示在可视化模板(ResourceDictionary 中的 xaml)中,如下所示:

+-------------+
| L |         |
| o |  Main   |
| g | Content |
| o |         |
+---+---------+
| Interaction |
+-------------+

屏幕的 Xaml 如下所示:

<controls:ScreenControl>
    <controls:ScreenControl.MainContent>
        <TextBlock>Some content goes here</TextBlock>
    </controls:ScreenControl.MainContent>
    <controls:ScreenControl.UserInteractions>
        <Button>Do something</Button>
    </controls:ScreenControl.UserInteractions>
</controls:InstallerScreenControl>

当我运行应用程序时,这很好用。但是,在设计器中,什么都看不见。不是视图中明确定义的内容,也不是模板中的内容。我需要添加什么来启用设计支持?我尝试按照某些地方的建议将模板移动到Themes/Generic.xaml,但这没有任何区别。 This SO question 似乎相关,但没有得到有用的答案。

编辑: 我的ScreenControl 看起来像这样:

public class ScreenControl : UserControl
{
    public object MainContent
    {
        get { return GetValue(MainContentProperty); }
        set { SetValue(MainContentProperty, value); }
    }
    public static readonly DependencyProperty MainContentProperty = DependencyProperty.Register(
        name: "MainContent",
        propertyType: typeof(object), 
        ownerType: typeof(ScreenControl),
        typeMetadata: new PropertyMetadata(default(object)));


    public object UserInteractions
    {
        get { return GetValue(UserInteractionsProperty); }
        set { SetValue(UserInteractionsProperty, value); }
    }
    public static readonly DependencyProperty UserInteractionsProperty = DependencyProperty.Register(
        name: "UserInteractions",
        propertyType: typeof(object),
        ownerType: typeof(ScreenControl),
        typeMetadata: new PropertyMetadata(default(object)));
}

当在设计器中查看使用该控件的屏幕时,它只显示:

即,什么都没有,只有一个空白框。

使用控件时,我创建了一个UserControl,添加了问题开头所示的 Xaml,并删除了代码隐藏文件。

【问题讨论】:

    标签: c# wpf xaml user-controls


    【解决方案1】:

    您必须从 Control 而不是 UserControl 继承自定义控件才能应用模板。

    很难用你提供的信息来判断,但你必须有一个静态构造函数来应用模板。

    public class ScreenControl : Control
    {
        static ScreenControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ScreenControl), new FrameworkPropertyMetadata(typeof(ScreenControl)));
        }
    }
    

    在进一步阅读时可能不是您的问题,不确定您在某处有一些 InDesignMode? 仅在应用程序运行时调用您的代码? IE WebService 调用?这里只是猜测,但很多事情可能会导致设计师崩溃。

    【讨论】:

    • 应用了模板,所以它在运行时工作,但在设计器模式下,它只是一个空白页(甚至不是设计器异常)。我将尝试在问题中澄清。真的,还没有外部电话或其他任何东西。只是视觉效果。
    • 我尝试从 Control 继承而不是 UserControl,但在设计时或运行时都看不到任何区别。
    • 重写 OnApplyTemplate 方法并在那里设置一个断点,看看它是否在你的设计器中被调用。
    • (对于像我一样不知道如何调试设计器的未来读者,请查看stackoverflow.com/a/12843372/124178
    • 这个被接受的答案是实际的解决方案吗?它与WPF有关吗?我在 WinRT-XAML 中遇到了完全相同的问题,并且提出的解决方案根本无法编译。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 2023-03-06
    • 2017-07-10
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    相关资源
    最近更新 更多