因为WPF默认的窗体比较简陋,大都需要自己实现Window窗体样式效果,基本思路:
第一步:取消默认样式:WindowStyle = WindowStyle.None;
第二步:设置窗体透明:AllowsTransparency = true;
第三步:设置自己的窗体样式;
代码:
#region CaptionForeground 标题栏前景景色
public static readonly DependencyProperty CaptionForegroundProperty = DependencyProperty.Register(
"CaptionForeground", typeof(Brush), typeof(WindowBase), new PropertyMetadata(null));
public Brush CaptionForeground
{
get { return (Brush)GetValue(CaptionForegroundProperty); }
set { SetValue(CaptionForegroundProperty, value); }
}
#endregion
#region Header 标题栏内容模板,以提高默认模板,可自定义
public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register(
"Header", typeof(ControlTemplate), typeof(WindowBase), new PropertyMetadata(null));
public ControlTemplate Header
{
get { return (ControlTemplate)GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
#endregion
绑定命令的扩展方法:
public static void BindCommand(this UIElement @ui, ICommand com, Action<object, ExecutedRoutedEventArgs> call){
var bind = new CommandBinding(com);
bind.Executed += new ExecutedRoutedEventHandler(call);
@ui.CommandBindings.Add(bind);
}
WindowBase的样式有两个,一个是基础样式BaseWindowStyle,可以自定义头部标题栏,提供更多定制需求。另一个样式DefaultWindowStyle为默认窗体样式,用于大多数不要特别定制的窗体需求。BaseWindowStyle样式代码:
<Setter Property = "Template" >
< Setter.Value >
< ControlTemplate TargetType="{x:Type local:WindowBase}">
<Grid Margin = "6" >
< !--背景-- >
< Border x:Name="Bg" CornerRadius="{TemplateBinding local:ControlAttachProperty.CornerRadius}"
Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" Effect="{StaticResource WindowDropShadow}"
<Grid Margin = "1" >
< Grid.RowDefinitions >
< RowDefinition MinHeight="18" Height="Auto"/>
<RowDefinition Height = "*" />
</ Grid.RowDefinitions >
< !--Caption标题部分-- >
< Border Margin="0" Grid.Row="0" Background="{TemplateBinding CaptionBackground}">
<Grid Margin = "2,1,2,0" >
< Grid.ColumnDefinitions >
< ColumnDefinition Width="*"/>
<ColumnDefinition Width = "Auto" />
</ Grid.ColumnDefinitions >
</ Grid >
</ Border >
< AdornerDecorator Grid.Row= "1" Margin= "3,0,3,3" >
< ContentPresenter Content= "{TemplateBinding Content}" />
</ AdornerDecorator >
</ Grid >
</ Grid >
< ControlTemplate.Triggers >
< Trigger Property= "WindowState" Value= "Maximized" >
< Setter Property= "FIcon" TargetName= "btnMax" Value= "" ></ Setter >
</ Trigger >
< Trigger Property= "WindowState" Value= "Normal" >
< Setter Property= "FIcon" TargetName= "btnMax" Value= "" ></ Setter >
</ Trigger >
</ ControlTemplate.Triggers >
</ ControlTemplate >
</ Setter.Value >
</ Setter >