我想制作一些我常用的 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/