我目前正在编写一个扩展Window的Dialog类(无视控件),并使用XAML样式为该类分配一个默认的ControlTemplate .
我希望我的Dialog模板的'Buttons'部分可以替换,但如果没有指定其他内容,则使用一组默认按钮预先填充它 . 这就是为什么我在我的 class 中添加了一个名为 ButtonContent
的 dependency property .
DefaultButtons
(参见下面的XAML)是 rendered correctly when I run the application ,但 Visual Studio 2010's design preview does not render the content . 为什么这不会发生?
我的对话框类看起来像这样:
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)));
}
}
这是我的XAML:
<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>
当我启动应用程序时,它看起来像这样:
As rendered by the app http://i48.tinypic.com/1t6fbp.png
VS2010设计师提出:
As rendered by VS2010 http://i50.tinypic.com/nxw9bk.png
Edit: 如评论中所述,将上述样式放在Themes \ Generic.xaml中而不是App.xaml中包含的我的资源字典不会改变任何内容 .
Edit 2: 如果我像这样明确覆盖默认的 ButtonContent
,设计师也不会显示任何内容 . 在运行时,一切都很完美:
<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>
Edit 3: 如果我将 ButtonContent
属性添加到 UserControl
而不是扩展 Window
的 Dialog
类,则 ButtonContent
在用户控件中正确显示...同样,VS2010似乎将上面定义的样式应用于任何窗口,而不仅仅是类的窗口 Dialog
,虽然我已经适当地设置了TargetType ......很奇怪!
1 回答
我在Microsoft Connect上为此问题打开了一个bug report . 根据MS,这是一个已知的问题,并且是设计的: