c# - 在 WPF 中指定自定义窗口的默认外观?

标签 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)));
    } 
}

窗口样式。位于控件库Themes文件夹下的一个Generic.xaml,一个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 和黑色背景的窗口。

最佳答案

使用这个 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>

关于c# - 在 WPF 中指定自定义窗口的默认外观?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6599412/

相关文章:

javascript - Meteor - 如何在模板事件函数中正确路由

c++ - 抽象类分类的模板语法

c# - 是否可以为 List<double> 预分配内存?

wpf - 播放完 MediaElement 后,如何再次播放?

wpf - 控件不显示在 Winforms 主机上

wpf - 在带有 WPF 的 MVVM 中,如何对 ViewModel 和 View 之间的链接进行单元测试

c++ - 编译时专门针对函数指针引用以避免 -Waddress

c# - 打开 XML SDK : Format part of an Excel-cell

c# - 匿名类型的单元测试 - JSON

c# - 将 XDocument 和 XmlReader 降级为 XmlDocument 和 XmlReader