我想为一些常用的WPF控件创建一个库,其中一个控件是从Window
类继承的CustomWindow
。如何让我的CustomWindow
使用库中定义的默认外观?
我可以更换
<Window x:Class="..." />
带有
<MyControls:CustomWindow x:Class="..." />
它适用于窗口行为,但不适用于外观。
编辑
以下是我迄今为止的简化版本:
自定义窗口控件。位于控制库中。
public class CustomChromeWindow: Window
{
static CustomChromeWindow()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomChromeWindow),
new FrameworkPropertyMetadata(typeof(CustomChromeWindow)));
}
}
窗口样式。位于控制库的主题文件夹中的资源字典Generic.xaml中
<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>
尝试将其添加到类库中的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)
)]
这个怎么样(把它放在默认的Cctor中(:
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomWindow)
, new FrameworkPropertyMetadata(typeof(CustomWindow)));`