在WPF中指定自定义Window的默认外观?

时间:2011-07-06 15:56:56

标签: c# wpf templates window styles

我想创建一些常用的WPF控件库,其中一个控件是CustomWindow,它继承自Window类。如何让我的CustomWindow使用库中定义的默认外观?

我可以替换

<Window x:Class="..." />

<MyControls:CustomWindow x:Class="..." />

它适用于窗口行为,但不适用于出现。

修改

以下是我到目前为止的简化版本:

自定义窗口控件。位于控制库中。

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

窗口样式。位于Generic.xaml中,是控件库的Themes文件夹中的ResourceDictionary

<Style TargetType="local:CustomChromeWindow">
    <Setter Property="WindowStyle" Value="None" />
    <Setter Property="Background" Value="Red" />
</Style>

测试窗口。引用控件库的单独项目的启动窗口

<local:CustomChromeWindow
    x:Class="MyControlsTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyControls;assembly=MyControls"
    Title="MainWindow" Height="350" Width="525"
    >
    <Grid>
        <TextBlock Text="This is a Test" />
    </Grid>
</local:CustomChromeWindow>

我最终获得的是一个带有常规WindowStyle和黑色背景的窗口。

3 个答案:

答案 0 :(得分:2)

使用此xaml:

<Window x:Class="MyNamespace.CustomWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:MyControls="MyNamespace">

    <Window.Style>
        <Style TargetType="MyControls:CustomWindow">
        ...
        </Style>
    </Window.Style>

    <ContentPresenter />

</Window>

您可能想为窗口设计一个新主题。如果是这样,请在(您的库)\ Themes \ Generic.xaml资源文件中放置以下主题:

<Style TargetType="{x:Type MyControls:CustomWindow}">
    <Setter Property="WindowStyle" Value="None" />
    <Setter Property="AllowsTransparency" Value="True" />
    ...

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type MyControls:CustomWindow}">
                <Border>
                    ...
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

答案 1 :(得分:1)

尝试将其添加到类库中的AssemblyInfo.cs文件

[assembly: ThemeInfo(
    ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
    //(used if a resource is not found in the page, 
    // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
    //(used if a resource is not found in the page, 
    // app, or any theme specific resource dictionaries)
)]

答案 2 :(得分:0)

这个怎么样(把它放在默认的Cctor中):

 DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomWindow)
                                             , new FrameworkPropertyMetadata(typeof(CustomWindow)));`