扩展Window类的ContentPresenter在设计时不显示内容

时间:2012-10-30 17:44:40

标签: c# wpf visual-studio-2010 dependency-properties contentpresenter

我目前正在编写一个扩展Window的Dialog类(无视控件),并使用XAML样式为该类分配一个默认的ControlTemplate。

我希望我的Dialog模板的'Buttons'部分可以替换,但如果没有指定其他内容,则用一组默认按钮预先填充它。这就是为什么我在我的班级中添加了一个名为ButtonContent依赖属性

运行应用程序时<{1}}(请参阅下面的XAML)正确呈现,但 Visual Studio 2010的设计预览不会呈现内容。为什么不发生这种情况?

我的对话框类看起来像这样:

DefaultButtons

这是我的XAML:

public class Dialog : Window
{
    public FrameworkElement ButtonContent
    {
        get { return (FrameworkElement)GetValue(ButtonContentProperty); }
        set { SetValue(ButtonContentProperty, value); }
    }

    public static readonly DependencyProperty ButtonContentProperty =
        DependencyProperty.Register("ButtonContent", typeof(FrameworkElement), typeof(Dialog), new UIPropertyMetadata(null));

    static Dialog()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(Dialog), new FrameworkPropertyMetadata(typeof(Dialog)));
    }
}

当我启动应用时,它看起来像这样:

As rendered by the app http://i48.tinypic.com/1t6fbp.png

VS2010设计师提出:

As rendered by VS2010 http://i50.tinypic.com/nxw9bk.png


编辑如评论中所述,将上述样式放在Themes \ Generic.xaml而不是App.xaml中包含的资源字典中,不会改变任何内容。


编辑2:如果我明确覆盖默认的<Style TargetType="{x:Type Dialogs:Dialog}"> <Setter Property="DataContext" Value="{Binding RelativeSource={RelativeSource Self}}"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Dialogs:Dialog}"> <StackPanel> <ContentPresenter Content="{TemplateBinding ButtonContent}"/> <TextBlock>This text is rendered correctly</TextBlock> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="ButtonContent"> <Setter.Value> <!-- This stuff here is not shown in VS2010's preview --> <UniformGrid Name="DefaultButtons" Rows="1" Columns="2"> <Button>Button 1</Button> <Button>Button 2</Button> </UniformGrid> </Setter.Value> </Setter> </Style> ,设计师也不会显示任何内容。在运行时,一切都很完美:

ButtonContent

修改3 :如果我将<Dialogs:Dialog x:Class="Dialogs.TestDialog" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Dialogs="clr-namespace:Dialogs"> <Dialogs:Dialog.ButtonContent> <Button>Also not shown at design time</Button> </Dialogs:Dialog.ButtonContent> </Dialogs:Dialog> 属性添加到ButtonContent而不是UserControl扩展Dialog的{​​{1}}类,{{ 1}}在用户控件中正确显示...同样,VS2010似乎将上面定义的样式应用于任何窗口,而不仅仅是类Window的窗口,尽管我已经设置了TargetType恰当......怪异!

1 个答案:

答案 0 :(得分:1)

我在Microsoft Connect上为此问题打开了bug report。根据MS,这是一个已知的问题,并且是设计的:

  

感谢您报告此问题。这是我们的一个已知问题,并且是设计上的。我们无法在设计器中创建Window的设计实例,因此我们使用自己的代理类型替换。这就是为什么它在UserControl中正常工作而不是在窗口中的原因。解决方法是将对话框的内容分别设计为UserControl。