为什么我的UserControl不会显示在设计器中?

时间:2014-07-23 09:36:57

标签: c# wpf xaml user-controls

我已经实现了一个用户控件,可以让我快速构建几个类似的界面屏幕。基本上它定义了两个依赖属性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)));
}

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

Nothing here...

是的,没什么,只是一个空白的盒子。

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

1 个答案:

答案 0 :(得分:2)

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

很难说明您提供的信息,但您必须拥有一个应用模板的静态构造函数。

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

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