【NEW】WPF MVVM 模式下自写自用的窗口样式

2022-09-01 17:26:48 浏览数 (1)

这是全新版本,可以自定义【图标】【图标颜色】【字体颜色】【窗体样式】【窗体颜色】

总之而言就是,界面上能看到的你都可以动态修改与动态切换

先来说说图片的颜色该怎么自定义

我这里用的到是SVG的图片资源

SVG是一种图形文件格式,它的英文全称为Scalable Vector Graphics,意思为可缩放的矢量图形。它是基于XML(Extensible Markup Language),由World Wide Web Consortium(W3C)联盟进行开发的。严格来说应该是一种开放标准的矢量图形语言,可让你设计激动人心的、高分辨率的Web图形页面。用户可以直接用代码来描绘图像,可以用任何文字处理工具打开SVG图像,通过改变部分代码来使图像具有交互功能,并可以随时插入到HTML中通过浏览器来观看。

WPF默认是不支持SVG文件的直接显示,我们得手动更改,当然你也可以写工具一键更改

实现步骤:

1.直接到 https://www.iconfont.cn 中选取合适图标,点击下载

2.复制SVG代码

3.你会得到一个XML格式的SVG文件

4.这时你就会发现,有两个path,你只要把【d】里面的数据单独复制出来

5.然后以下面这种方式放进一个你定义好的资源文件中

代码语言:javascript复制
<!--一定要写注释哦-->
<DrawingImage x:Key="给这个资源定个名称">
    <DrawingImage.Drawing>
        <DrawingGroup>
            <GeometryDrawing Brush="这里面是颜色"  Geometry="把已复制的数据按顺序复制进来" />
            <GeometryDrawing Brush="这里面是颜色"  Geometry="把已复制的数据按顺序复制进来" />
        </DrawingGroup>
    </DrawingImage.Drawing>
</DrawingImage>

Copy

注意:并不是所有图标SVG都是两个path,有多有少,【GeometryDrawing】跟【path】的数量对应后粘贴数据即可

6.这是时候,你在你的App.xaml中引用这个资源字典

代码语言:javascript复制
<Application.Resources>
       <ResourceDictionary>
           <ResourceDictionary.MergedDictionaries>
               <ResourceDictionary Source="pack://application:,,,/【解决方案名称】;component/【路径】/资源文件名称.xaml" />
           </ResourceDictionary.MergedDictionaries>
       </ResourceDictionary>
   </Application.Resources>

Copy

7.你已经可以使用这个SVG格式的图片资源了,颜色也可以自定义了

代码语言:javascript复制
<Image Source="{DynamicResource 资源x:Key名称}"/>

Copy

以上是自定义图片资源与颜色,上面懂了,下面就好办了

开始正题,总共使用三个解决方案

1.Window实现集成基类

2.MessageBox弹窗类

3.MVVM模式扩展方法

Window实现集成基类

ButtonStyle.xaml

代码语言:javascript复制
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                     xmlns:sv="clr-namespace:WindowHelper">


    <!--标题按钮样式-->
    <Style x:Key="CaptionButtonStyle"  TargetType="{x:Type Button}">
        <Setter Property="Focusable" Value="False"/>
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="OverridesDefaultStyle" Value="True"/>
        <Setter Property="Margin" Value="0"/>
    </Style>

    <!--最小化按钮样式-->
    <ControlTemplate x:Key="MinCaptionButtonStyle" TargetType="{x:Type Button}">
        <Border Name="minborder">
                        <ContentPresenter  HorizontalAlignment="Center" VerticalAlignment="Center" ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"  RecognizesAccessKey="True" Content="{TemplateBinding ContentControl.Content}" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <!--被按下-->
                        <Trigger Property="IsPressed" Value="True">
                <Setter Property="Background" TargetName="minborder" Value="{DynamicResource CaptionButtonPressedBackgroundBrush}"/>
                <Setter Property="BorderBrush" TargetName="minborder" Value="{DynamicResource CaptionButtonHighlightBorderBrush}"/>
                        </Trigger>
                        <!--多条件触发-->
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <!--被按下-->
                                <Condition Property="IsPressed" Value="False"/>
                                <!--鼠标在上方-->
                                <Condition Property="IsMouseOver" Value="True"/>
                            </MultiTrigger.Conditions>
                <Setter Property="Background" TargetName="minborder" Value="{DynamicResource CaptionButtonBackgroundBrush}"/>
                <Setter Property="BorderBrush" TargetName="minborder" Value="{DynamicResource CaptionButtonHighlightBorderBrush}"/>
                        </MultiTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>


    <!--最大化按钮样式-->
    <ControlTemplate x:Key="MaxCaptionButtonStyle" TargetType="{x:Type Button}">
        <Border Name="maxborder">
            <ContentPresenter  HorizontalAlignment="Center" VerticalAlignment="Center" ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"  RecognizesAccessKey="True" Content="{TemplateBinding ContentControl.Content}" />
        </Border>
        <ControlTemplate.Triggers>
            <!--被按下-->
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="Background" TargetName="maxborder" Value="{DynamicResource CaptionButtonPressedBackgroundBrush}"/>
                <Setter Property="BorderBrush" TargetName="maxborder" Value="{DynamicResource CaptionButtonHighlightBorderBrush}"/>
            </Trigger>
            <!--多条件触发-->
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <!--被按下-->
                    <Condition Property="IsPressed" Value="False"/>
                    <!--鼠标在上方-->
                    <Condition Property="IsMouseOver" Value="True"/>
                </MultiTrigger.Conditions>
                <Setter Property="Background" TargetName="maxborder" Value="{DynamicResource CaptionButtonBackgroundBrush}"/>
                <Setter Property="BorderBrush" TargetName="maxborder" Value="{DynamicResource CaptionButtonHighlightBorderBrush}"/>
            </MultiTrigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>

    <!--关闭按钮样式-->
    <ControlTemplate x:Key="CloseCaptionButtonStyle" TargetType="{x:Type Button}">
        <Border Name="closeborder">
            <ContentPresenter  HorizontalAlignment="Center" VerticalAlignment="Center" ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"  RecognizesAccessKey="True" Content="{TemplateBinding ContentControl.Content}" />
        </Border>
        <ControlTemplate.Triggers>
            <!--被按下-->
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="Background" TargetName="closeborder" Value="{DynamicResource CloseCaptionButtonPressedBackgroundBrush}"/>
                <Setter Property="BorderBrush" TargetName="closeborder" Value="{DynamicResource CloseCaptionButtonHighlightBorderBrush}"/>
                <Setter Property="CornerRadius" TargetName="closeborder" Value="{DynamicResource CloseCornerRadius}"/>
            </Trigger>
            <!--多条件触发-->
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <!--被按下-->
                    <Condition Property="IsPressed" Value="False"/>
                    <!--鼠标在上方-->
                    <Condition Property="IsMouseOver" Value="True"/>
                </MultiTrigger.Conditions>
                <Setter Property="Background" TargetName="closeborder" Value="{DynamicResource CloseCaptionButtonBackgroundBrush}"/>
                <Setter Property="BorderBrush" TargetName="closeborder" Value="{DynamicResource CloseCaptionButtonHighlightBorderBrush}"/>
                <Setter Property="CornerRadius" TargetName="closeborder" Value="{DynamicResource CloseCornerRadius}"/>
                <Setter Property="Opacity" TargetName="closeborder" Value="0.8"/>
            </MultiTrigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</ResourceDictionary>

Copy

ResizeGripStyle.xaml

代码语言:javascript复制
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!--调整控制方式-->
    <Style TargetType="{x:Type ResizeGrip}" x:Key="ResizeGripStyle">
        <Setter Property="IsTabStop" Value="False"/>
        <Setter Property="Margin" Value="0,0,4,4"/>
        <Setter Property="MinWidth" Value="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}"/>
        <Setter Property="MinHeight" Value="{DynamicResource {x:Static SystemParameters.HorizontalScrollBarHeightKey}}"/>
        <Setter Property="MaxWidth" Value="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}"/>
        <Setter Property="MaxHeight" Value="{DynamicResource {x:Static SystemParameters.HorizontalScrollBarHeightKey}}"/>
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ResizeGrip}">
                    <Grid
             Background="{TemplateBinding Panel.Background}"
             SnapsToDevicePixels="True">
                        <Path
               Margin="0,0,2,2"
               Data="M8,0L10,0 10,2 8,2z M4,4L6,4 6,6 4,6z M8,4L10,4 10,6 8,6z M0,8L2,8 2,10 0,10z M4,8L6,8 6,10 4,10z M8,8L10,8 10,10 8,10z"
               HorizontalAlignment="Right"
               Fill="#B1C9E8"
               VerticalAlignment="Bottom"/>
                        <Path
               Margin="0,0,3,3"
               Data="M8,0L10,0 10,2 8,2z M4,4L6,4 6,6 4,6z M8,4L10,4 10,6 8,6z M0,8L2,8 2,10 0,10z M4,8L6,8 6,10 4,10z M8,8L10,8 10,10 8,10z"
               HorizontalAlignment="Right"
               Fill="#455D80"
               VerticalAlignment="Bottom"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>

Copy

ThumbStyle.xaml

代码语言:javascript复制
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                    mc:Ignorable="d">
    <!--Simple Simple SliderThumb - Thumb 是 Slider 的可拖动部分-->
    <Style x:Key="SimpleSliderThumb" d:IsControlPart="True" TargetType="{x:Type Thumb}">
        <Setter Property="SnapsToDevicePixels" Value="true"/>
        <Setter Property="Height" Value="14"/>
        <Setter Property="Width" Value="14"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Thumb}">
                    <Grid>
                        <Rectangle StrokeThickness="0" Fill="#00000000"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True"/>
                        <Trigger Property="IsEnabled" Value="false"/>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Copy

WindowStyle.xaml

代码语言:javascript复制
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sv="clr-namespace:WindowHelper">

    <!--窗体样式-->
    <Style x:Key="StyleBase" TargetType="{x:Type sv:WindowBase}">
        <Setter Property="Window.WindowStyle" Value="None"/>
        <Setter Property="AllowsTransparency" Value="True"/>
        <Setter Property="TextElement.Foreground" Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"/>
        <Setter Property="TextElement.Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
        <Setter Property="Border.BorderThickness" Value="1.5"/>
        <Setter Property="Border.BorderBrush" Value="{DynamicResource WindowBorderBrush}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type sv:WindowBase}">
                    <Border CornerRadius="{DynamicResource WindowCornerRadius}"  Background="{DynamicResource WindowContentBackground}" Margin="20"  Name="WindowFrame">
                        <Border.Effect >
                            <DropShadowEffect BlurRadius="15" ShadowDepth="0.5" Opacity="0.5"/>
                        </Border.Effect>
                        <Grid Background="Transparent" >
                            <Grid.RowDefinitions>
                                <RowDefinition Height="auto"/>
                                <RowDefinition/>
                                <RowDefinition Height="auto"/>
                            </Grid.RowDefinitions>
                            <!--标题-->
                            <Border Height="{DynamicResource TitleHeight}" Name="PART_Caption" Grid.Row="0" CornerRadius="{DynamicResource TopCornerRadius}" Background="{DynamicResource CaptionActiveBackgroundBrush}">
                                <Border.Effect>
                                    <DropShadowEffect BlurRadius="5" ShadowDepth="0.5" Opacity="0.3" />
                                </Border.Effect>
                                <!--标题-->
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="auto"/>
                                        <ColumnDefinition/>
                                        <ColumnDefinition Width="40"/>
                                        <ColumnDefinition Width="40"/>
                                        <ColumnDefinition Width="40"/>
                                    </Grid.ColumnDefinitions>
                                    <!--LOGO-->
                                    <Image Grid.Column="0" Source="{Binding Path=Icon, RelativeSource={RelativeSource TemplatedParent}}" Margin="5" Name="PART_Icon"/>
                                    <!--标题-->
                                    <Label  Name="CaptionText" Grid.Column="1"  Content="{Binding Path=Title, RelativeSource={RelativeSource TemplatedParent}}" VerticalAlignment="Center" HorizontalAlignment="{DynamicResource TitleHorizontalAlignment}"  Foreground="{DynamicResource TitleForeground}" FontWeight="{DynamicResource TitleFontWeight}" FontSize="{DynamicResource TitleFontSize}" />
                                    <!--最小化-->
                                    <Button  Grid.Column="2" Background="{x:Null}" BorderThickness="0" Style="{DynamicResource CaptionButtonStyle}" Template="{DynamicResource MinCaptionButtonStyle}"  Name="PART_MinimizeButton">
                                        <StackPanel Orientation="Horizontal">
                                            <Image  Source="{DynamicResource Min}" Width="{DynamicResource MinimizeImageWidth}" />
                                        </StackPanel>
                                    </Button>
                                    <!--最大化-->
                                    <Button  Grid.Column="3" Background="{x:Null}" BorderThickness="0" Style="{DynamicResource CaptionButtonStyle}" Template="{DynamicResource MaxCaptionButtonStyle}" Name="PART_MaximizeButton" >
                                        <StackPanel Orientation="Horizontal" >
                                            <Image Source="{DynamicResource Max}" Width="{DynamicResource MaximizeImageWidth}" />
                                        </StackPanel>
                                    </Button>
                                    <!--关闭-->
                                    <Button  Grid.Column="4" Background="{x:Null}" BorderThickness="0" Style="{DynamicResource CaptionButtonStyle}" Template="{DynamicResource CloseCaptionButtonStyle}"  Name="PART_CloseButton">
                                        <StackPanel Orientation="Horizontal">
                                            <Image  Source="{DynamicResource Close}" Width="{DynamicResource CloseImageWidth}" />
                                        </StackPanel>
                                    </Button>
                                    <!--窗体移动工具-->
                                    <Border Name="WindowMoveGripper" CornerRadius="{DynamicResource TopCornerRadius}" Grid.Column="0" Grid.ColumnSpan="2" Margin="3,3,0,0">
                                        <Rectangle  IsHitTestVisible="False" Focusable="False" Fill="Transparent"/>
                                    </Border>
                                </Grid>
                            </Border>
                            <!--内容-->
                            <Border Name="PART_ClientArea" Grid.Row="1">
                                <Grid>
                                    <ContentPresenter ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}" Content="{TemplateBinding ContentControl.Content}" />
                                </Grid>
                            </Border>
                            <!--版本-->
                            <Border Grid.Row="2" BorderThickness="0,1,0,0" Height="{DynamicResource VerHeight}" VerticalAlignment="Bottom" CornerRadius="{DynamicResource DownCornerRadius}"   Background="{DynamicResource VerBackgroundBrush}" Name="PART_Ver">
                                <Border.Effect>
                                    <DropShadowEffect BlurRadius="5" ShadowDepth="0" Opacity="0.3" />
                                </Border.Effect>
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="auto"/>
                                        <ColumnDefinition Width="auto"/>
                                        <ColumnDefinition/>
                                    </Grid.ColumnDefinitions>
                                    <Image Grid.Column="0" Source="{DynamicResource Ver}" Margin="4,3,0,3" />
                                    <Label Grid.Column="1" Content="Ver :"  VerticalAlignment="Center" FontWeight="{DynamicResource VerFontWeight}"  Foreground="{DynamicResource VerForeground}" FontSize="{DynamicResource VerFontSize}"/>
                                    <Label Grid.Column="2" Name="System_Ver" Margin="-13,0,0,0" VerticalAlignment="Center" FontWeight="{DynamicResource VerCodeFontWeight}"  Foreground="{DynamicResource VerCodeForeground}" FontSize="{DynamicResource VerCodeFontSize}"/>
                                </Grid>
                            </Border>

                            <!--移动工具-->
                            <ResizeGrip Grid.Row="0" Grid.RowSpan="3" x:Name="PART_ResizeGrip" HorizontalAlignment="Right" Style="{DynamicResource ResizeGripStyle}" VerticalAlignment="Bottom"  Cursor="SizeNWSE" Visibility="Collapsed"/>
                            <Thumb Grid.Row="0" Grid.RowSpan="3" x:Name="PART_LeftResizer" VerticalAlignment="Stretch" Margin="0" Style="{DynamicResource SimpleSliderThumb}" HorizontalAlignment="Left" Width="8" Height="Auto" Cursor="SizeWE"/>
                            <Thumb  Grid.Row="0" Grid.RowSpan="3" x:Name="PART_RightResizer" HorizontalAlignment="Right" Margin="0" Style="{DynamicResource SimpleSliderThumb}" VerticalAlignment="Stretch" Width="8" Height="Auto" Cursor="SizeWE"/>
                            <Thumb  Grid.Row="0" Grid.RowSpan="3" x:Name="PART_TopResizer" HorizontalAlignment="Stretch" Margin="0" Style="{DynamicResource SimpleSliderThumb}" VerticalAlignment="Top" Width="Auto" Height="8" Cursor="SizeNS"/>
                            <Thumb  Grid.Row="0" Grid.RowSpan="3" x:Name="PART_TopLeftResizer" HorizontalAlignment="Left" Style="{DynamicResource SimpleSliderThumb}" VerticalAlignment="Top" Width="8" Height="8" Cursor="SizeNWSE"/>
                            <Thumb  Grid.Row="0" Grid.RowSpan="3" x:Name="PART_BottomResizer" HorizontalAlignment="Stretch" Margin="0" Style="{DynamicResource SimpleSliderThumb}"  VerticalAlignment="Bottom" Width="Auto" Height="8" Cursor="SizeNS"/>
                            <Thumb  Grid.Row="0" Grid.RowSpan="3" x:Name="PART_TopRightResizer" HorizontalAlignment="Right" Style="{DynamicResource SimpleSliderThumb}" VerticalAlignment="Top" Width="8" Height="8" Cursor="SizeNESW"/>
                            <Thumb  Grid.Row="0" Grid.RowSpan="3" x:Name="PART_BottomLeftResizer" HorizontalAlignment="Left" Style="{DynamicResource SimpleSliderThumb}" VerticalAlignment="Bottom" Width="8" Height="8" Cursor="SizeNESW"/>
                            <Thumb  Grid.Row="0" Grid.RowSpan="3" x:Name="PART_BottomRightResizer" HorizontalAlignment="Right" Style="{DynamicResource SimpleSliderThumb}" VerticalAlignment="Bottom" Width="8" Height="8" Cursor="SizeNWSE"/>

                        </Grid>

                    </Border>
                    <!--控件模板触发器-->
                    <ControlTemplate.Triggers>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="ResizeMode" Value="CanResizeWithGrip"/>
                                <Condition Property="WindowState" Value="Normal" />
                            </MultiTrigger.Conditions>
                            <Setter Property="Visibility" TargetName="PART_ResizeGrip" Value="Visible"/>
                        </MultiTrigger>
                        <Trigger Property="WindowState" Value="Maximized">
                            <Setter Property="CornerRadius" TargetName="WindowFrame" Value="0"/>
                            <Setter Property="CornerRadius" TargetName="PART_Caption" Value="0"/>
                            <Setter Property="CornerRadius" TargetName="PART_Ver" Value="0"/>
                            <Setter Property="Margin" TargetName="WindowFrame" Value="0"/>
                        </Trigger>
                        <Trigger Property="WindowState" Value="Normal">
                            <Setter Property="Margin" TargetName="WindowFrame" Value="20"/>
                        </Trigger>
                    </ControlTemplate.Triggers>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Copy

SvgImage.xaml

代码语言:javascript复制
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
     <!--确认-->
    <DrawingImage x:Key="Confirm">
        <DrawingImage.Drawing>
            <DrawingGroup>
                <GeometryDrawing Brush="{DynamicResource ImageColor}"  Geometry="M512 170.666667a341.333333 341.333333 0 0 0-290.133333 521.216 42.666667 42.666667 0 0 1-72.533334 45.013333A424.874667 424.874667 0 0 1 85.333333 512C85.333333 276.352 276.352 85.333333 512 85.333333s426.666667 191.018667 426.666667 426.666667-191.018667 426.666667-426.666667 426.666667a424.874667 424.874667 0 0 1-234.666667-70.314667 42.666667 42.666667 0 1 1 46.933334-71.210667A341.333333 341.333333 0 1 0 512 170.666667z m222.165333 264.832a42.666667 42.666667 0 0 0-60.330666-60.330667L469.333333 579.669333l-119.168-119.168a42.666667 42.666667 0 0 0-60.330666 60.330667l149.333333 149.333333a42.666667 42.666667 0 0 0 60.330667 0l234.666666-234.666666z" />
            </DrawingGroup>
        </DrawingImage.Drawing>
    </DrawingImage>

    <!--取消-->
    <DrawingImage x:Key="Cancel">
        <DrawingImage.Drawing>
            <DrawingGroup>
                <GeometryDrawing Brush="{DynamicResource ImageColor}"  Geometry="M170.666667 512a341.333333 341.333333 0 1 1 153.6 285.141333 42.666667 42.666667 0 1 0-46.933334 71.253334A424.874667 424.874667 0 0 0 512 938.666667c235.648 0 426.666667-191.018667 426.666667-426.666667S747.648 85.333333 512 85.333333 85.333333 276.352 85.333333 512c0 82.474667 23.466667 159.573333 64 224.896a42.666667 42.666667 0 0 0 72.533334-45.013333A339.541333 339.541333 0 0 1 170.666667 512z m183.168-158.165333a42.666667 42.666667 0 0 1 60.330666 0L512 451.669333l97.834667-97.834666a42.666667 42.666667 0 1 1 60.330666 60.330666L572.330667 512l97.834666 97.834667a42.666667 42.666667 0 0 1-60.330666 60.330666L512 572.330667l-97.834667 97.834666a42.666667 42.666667 0 0 1-60.330666-60.330666L451.669333 512 353.834667 414.165333a42.666667 42.666667 0 0 1 0-60.330666z" />
            </DrawingGroup>
        </DrawingImage.Drawing>
    </DrawingImage>
    <!--最大化-->
    <DrawingImage x:Key="Max">
        <DrawingImage.Drawing>
            <DrawingGroup>
                <GeometryDrawing Brush="{DynamicResource Max.ImageColor}"  Geometry="M900 64H360c-33.137 0-60 26.863-60 60v146H124c-33.137 0-60 26.863-60 60v570c0 33.137 26.863 60 60 60h570c33.137 0 60-26.863 60-60V724h146c33.137 0 60-26.863 60-60V124c0-33.137-26.863-60-60-60zM664 634v176c0 33.137-26.863 60-60 60H214c-33.137 0-60-26.863-60-60V420c0-33.137 26.863-60 60-60h390c33.137 0 60 26.863 60 60v214z m206-60c0 33.137-26.863 60-60 60h-56V330c0-33.137-26.863-60-60-60H390v-56c0-33.137 26.863-60 60-60h360c33.137 0 60 26.863 60 60v360z" />
            </DrawingGroup>
        </DrawingImage.Drawing>
    </DrawingImage>

    <!--最小化-->
    <DrawingImage x:Key="Min">
        <DrawingImage.Drawing>
            <DrawingGroup>
                <GeometryDrawing Brush="{DynamicResource Min.ImageColor}"  Geometry="M800 452H224c-33.137 0-60 26.863-60 60s26.863 60 60 60h576c33.137 0 60-26.863 60-60s-26.863-60-60-60z" />
            </DrawingGroup>
        </DrawingImage.Drawing>
    </DrawingImage>

    <!--关闭-->
    <DrawingImage x:Key="Close">
        <DrawingImage.Drawing>
            <DrawingGroup>
                <GeometryDrawing Brush="{DynamicResource Close.ImageColor}"  Geometry="M828.784 828.784c-23.431 23.431-61.421 23.431-84.853 0L195.216 280.069c-23.431-23.431-23.431-61.421 0-84.853 23.431-23.431 61.421-23.431 84.853 0l548.715 548.715c23.431 23.431 23.431 61.421 0 84.853z" />
                <GeometryDrawing Brush="{DynamicResource Close.ImageColor}"  Geometry="M195.216 828.784c-23.431-23.431-23.431-61.421 0-84.853l548.715-548.715c23.431-23.431 61.421-23.431 84.853 0 23.431 23.431 23.431 61.421 0 84.853L280.069 828.784c-23.431 23.431-61.421 23.431-84.853 0z" />
            </DrawingGroup>
        </DrawingImage.Drawing>
    </DrawingImage>

    <!--版本-->
    <DrawingImage x:Key="Ver">
        <DrawingImage.Drawing>
            <DrawingGroup>
                <GeometryDrawing Brush="{DynamicResource Ver.ImageColor}"  Geometry="M885.438 557.919c25.695-51.52 40.545-109.247 40.545-170.527C925.983 173.44 749.918 0 532.769 0 315.614 0 139.552 173.44 139.552 387.424c0 61.28 14.847 119.007 40.542 170.525L20.48 830.303c0 0 101.215 20.285 203.904 41.44 68.48 76.19 136.64 152.255 136.64 152.255l146.75-250.429c8.32 0.51 16.545 1.245 24.995 1.245 8.445 0 16.7-0.735 24.99-1.245l146.75 250.429c0 0 68.16-76.03 136.61-152.255 102.69-21.155 203.935-41.44 203.935-41.44L885.438 557.919zM353.407 907.838c0 0-49.152-46.59-95.36-91.52-65.535-18.625-131.68-37.63-131.68-37.63l92.8-158.275c53.505 69.795 130.272 121.025 219.104 142.655L353.407 907.838zM532.769 704.253c-176.577 0-319.682-143.425-319.682-320.349 0-176.897 143.137-320.319 319.682-320.319 176.54 0 319.679 143.422 319.679 320.319C852.448 560.829 709.308 704.253 532.769 704.253zM807.488 816.318c-46.21 44.93-95.36 91.52-95.36 91.52l-84.835-144.77c88.835-21.63 165.6-72.86 219.104-142.655l92.77 158.305C939.133 778.688 873.023 797.663 807.488 816.318zM532.769 160c-123.715 0-224.002 100.287-224.002 223.999s100.287 223.999 224.002 223.999c123.71 0 223.999-100.287 223.999-223.999S656.478 160 532.769 160zM532.769 543.999c-88.355 0-160.002-71.647-160.002-160s71.647-160 160.002-160c88.35 0 160 71.647 160 160S621.118 543.999 532.769 543.999z" />
            </DrawingGroup>
        </DrawingImage.Drawing>
    </DrawingImage>

</ResourceDictionary>

Copy

注意:这是模板了,属性都是一样的,数据不是一样的,我就展示两个

 Blue.xaml

代码语言:javascript复制
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib">

    <!--区域头 字体颜色-->
    <SolidColorBrush x:Key="Font.Head.Foreground" Color="#1296DB"/>
    <!--区域内容 字体颜色-->
    <SolidColorBrush x:Key="Font.Content.Foreground" Color="#5696DD"/>
    <!--图标颜色-->
    <SolidColorBrush x:Key="ImageColor" Color="#5696DD"/>

    <!--最小化图标颜色-->
    <SolidColorBrush x:Key="Min.ImageColor" Color="White"/>
    <!--最大化图标颜色-->
    <SolidColorBrush x:Key="Max.ImageColor" Color="White"/>
    <!--关闭图标颜色-->
    <SolidColorBrush x:Key="Close.ImageColor" Color="White"/>
    <!--版本图标颜色-->
    <SolidColorBrush x:Key="Ver.ImageColor" Color="White"/>

    <!--标题左右居中-->
    <!--<HorizontalAlignment x:Key="TitleHorizontalAlignment">Center</HorizontalAlignment>-->
    <HorizontalAlignment x:Key="TitleHorizontalAlignment">Left</HorizontalAlignment>

    <!--标题高度-->
    <sys:Double x:Key="TitleHeight">40</sys:Double>
    <!--标题的字体大小-->
    <sys:Double x:Key="TitleFontSize">16</sys:Double>
    <!--标题字体是否需要加粗-->
    <FontWeight x:Key="TitleFontWeight">Bold</FontWeight>
    <!--最小化图片宽度-->
    <sys:Double x:Key="MinimizeImageWidth">17</sys:Double>
    <!--最大化图片宽度-->
    <sys:Double x:Key="MaximizeImageWidth">17</sys:Double>
    <!--关闭图片宽度-->
    <sys:Double x:Key="CloseImageWidth">17</sys:Double>
    <!--版本的高度-->
    <sys:Double x:Key="VerHeight">25</sys:Double>
    <!--版本的展现内容-->
    <sys:String x:Key="VerContent">Ver :</sys:String>
    <!--版本的字体大小-->
    <sys:Double x:Key="VerFontSize">13</sys:Double>
    <!--版本号的字体大小-->
    <sys:Double x:Key="VerCodeFontSize">13</sys:Double>
    <!--版本字体是否需要加粗-->
    <FontWeight x:Key="VerFontWeight">Bold</FontWeight>
    <!--版本号字体是否需要加粗-->
    <FontWeight x:Key="VerCodeFontWeight">Bold</FontWeight>
    <!--所有字体样式-->
    <FontFamily x:Key="AllFontFamily">微软雅黑</FontFamily>

    <!--顶部的圆角控制-->
    <CornerRadius x:Key="TopCornerRadius"  TopLeft="10" TopRight="10" BottomLeft="0" BottomRight="0"/>
    <!--底部的圆角控制-->
    <CornerRadius x:Key="DownCornerRadius"  TopLeft="0" TopRight="0" BottomLeft="10" BottomRight="10"/>
    <!--关闭按钮的圆角控制-->
    <CornerRadius x:Key="CloseCornerRadius"  TopLeft="0" TopRight="10" BottomLeft="0" BottomRight="0"/>
    <!--窗口整体圆角控制-->
    <CornerRadius x:Key="WindowCornerRadius"  TopLeft="10" TopRight="10" BottomLeft="10" BottomRight="10"/>


    <!--鼠标在按钮上方时背景颜色-->
    <LinearGradientBrush x:Key="CaptionButtonBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#C6E5F8" Offset="0.123456" />
        <GradientStop Color="#24c2f8" Offset="0.987654" />
    </LinearGradientBrush>

    <!--按钮按下背景刷-->
    <LinearGradientBrush x:Key="CaptionButtonPressedBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#C6E5F0" Offset="0.123456" />
        <GradientStop Color="#24a2f0" Offset="0.987678" />
    </LinearGradientBrush>



    <!--鼠标在关闭按钮上方时背景颜色-->
    <LinearGradientBrush x:Key="CloseCaptionButtonBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#FF9B9D" Offset="0.123456" />
        <GradientStop Color="#FF464B" Offset="0.987654"/>
    </LinearGradientBrush>

    <!--关闭按钮按下背景刷-->
    <LinearGradientBrush x:Key="CloseCaptionButtonPressedBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#FF6A6C" Offset="0.123456" />
        <GradientStop Color="#FC292E" Offset="0.987678" />
    </LinearGradientBrush>

    <!--关闭按钮被按下布刷颜色-->
    <SolidColorBrush x:Key="CloseCaptionButtonHighlightBorderBrush" Color="#FC292E"/>


    <!--窗体标题背景色-->
    <LinearGradientBrush x:Key="CaptionActiveBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#5DA0EA" Offset="0.123456" />
        <GradientStop Color="#3a7bd5" Offset="0.987654" />
    </LinearGradientBrush>
    <!--版本背景色-->
    <LinearGradientBrush x:Key="VerBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#3a7bd5" Offset="0.123456" />
        <GradientStop Color="#5DA0EA" Offset="0.987654" />
    </LinearGradientBrush>

    <!--窗体的背景颜色-->
    <LinearGradientBrush x:Key="WindowContentBackground" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#F5F5F7" Offset="0"/>
        <GradientStop Color="#FFFFFF" Offset="0.5"/>
        <GradientStop Color="#F5F5F7" Offset="1"/>
    </LinearGradientBrush>

    <!--最大化最小化按钮被按下-->
    <SolidColorBrush x:Key="CaptionButtonHighlightBorderBrush" Color="#9EC2EF"/>
    <!--标题字体颜色-->
    <SolidColorBrush x:Key="TitleForeground" Color="White"/>
    <!--版本字体颜色-->
    <SolidColorBrush x:Key="VerForeground" Color="White"/>
    <!--版本号的字体颜色-->
    <SolidColorBrush x:Key="VerCodeForeground" Color="Red"/>
    <!--窗口边界颜色-->
    <SolidColorBrush x:Key="WindowBorderBrush" Color="#9EC2EF"/>
</ResourceDictionary>

Copy

Cyan.xaml

代码语言:javascript复制
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib">

    <!--区域头 字体颜色-->
    <SolidColorBrush x:Key="Font.Head.Foreground" Color="#05AFA7"/>
    <!--区域内容 字体颜色-->
    <SolidColorBrush x:Key="Font.Content.Foreground" Color="#028ea1"/>
    <!--图标颜色-->
    <SolidColorBrush x:Key="ImageColor" Color="#028ea1"/>

    <!--最小化图标颜色-->
    <SolidColorBrush x:Key="Min.ImageColor" Color="White"/>
    <!--最大化图标颜色-->
    <SolidColorBrush x:Key="Max.ImageColor" Color="White"/>
    <!--关闭图标颜色-->
    <SolidColorBrush x:Key="Close.ImageColor" Color="White"/>
    <!--版本图标颜色-->
    <SolidColorBrush x:Key="Ver.ImageColor" Color="White"/>

    <!--标题左右居中-->
    <!--<HorizontalAlignment x:Key="TitleHorizontalAlignment">Center</HorizontalAlignment>-->
    <HorizontalAlignment x:Key="TitleHorizontalAlignment">Left</HorizontalAlignment>
    <!--标题高度-->
    <sys:Double x:Key="TitleHeight">35</sys:Double>
    <!--标题的字体大小-->
    <sys:Double x:Key="TitleFontSize">15</sys:Double>
    <!--标题字体是否需要加粗-->
    <FontWeight x:Key="TitleFontWeight">Normal</FontWeight>
    <!--最小化图片宽度-->
    <sys:Double x:Key="MinimizeImageWidth">16</sys:Double>
    <!--最大化图片宽度-->
    <sys:Double x:Key="MaximizeImageWidth">16</sys:Double>
    <!--关闭图片宽度-->
    <sys:Double x:Key="CloseImageWidth">16</sys:Double>
    <!--版本的高度-->
    <sys:Double x:Key="VerHeight">25</sys:Double>
    <!--版本的字体大小-->
    <sys:Double x:Key="VerFontSize">13</sys:Double>
    <!--版本号的字体大小-->
    <sys:Double x:Key="VerCodeFontSize">13</sys:Double>
    <!--版本字体是否需要加粗-->
    <FontWeight x:Key="VerFontWeight">Normal</FontWeight>
    <!--版本号字体是否需要加粗-->
    <FontWeight x:Key="VerCodeFontWeight">Normal</FontWeight>
    <!--所有字体样式-->
    <FontFamily x:Key="AllFontFamily">微软雅黑</FontFamily>

    <!--顶部的圆角控制-->
    <CornerRadius x:Key="TopCornerRadius"  TopLeft="5" TopRight="5" BottomLeft="0" BottomRight="0"/>
    <!--底部的圆角控制-->
    <CornerRadius x:Key="DownCornerRadius"  TopLeft="0" TopRight="0" BottomLeft="5" BottomRight="5"/>
    <!--关闭按钮的圆角控制-->
    <CornerRadius x:Key="CloseCornerRadius"  TopLeft="0" TopRight="5" BottomLeft="0" BottomRight="0"/>
    <!--窗口整体圆角控制-->
    <CornerRadius x:Key="WindowCornerRadius"  TopLeft="5" TopRight="5" BottomLeft="5" BottomRight="5"/>

    <!--鼠标在按钮上方时背景颜色-->
    <LinearGradientBrush x:Key="CaptionButtonBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#83C9E2" Offset="0.123456" />
        <GradientStop Color="#06beb6" Offset="0.987654" />
    </LinearGradientBrush>

    <!--按钮按下背景刷-->
    <LinearGradientBrush x:Key="CaptionButtonPressedBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#83C9c9" Offset="0.123456" />
        <GradientStop Color="#06bec9" Offset="0.987678" />
    </LinearGradientBrush>


    <!--鼠标在关闭按钮上方时背景颜色-->
    <LinearGradientBrush x:Key="CloseCaptionButtonBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#FF9B9D" Offset="0.123456" />
        <GradientStop Color="#FF464B" Offset="0.987654"/>
    </LinearGradientBrush>

    <!--关闭按钮按下背景刷-->
    <LinearGradientBrush x:Key="CloseCaptionButtonPressedBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#FF6A6C" Offset="0.123456" />
        <GradientStop Color="#FC292E" Offset="0.987678" />
    </LinearGradientBrush>

    <!--关闭按钮被按下布刷颜色-->
    <SolidColorBrush x:Key="CloseCaptionButtonHighlightBorderBrush" Color="#FC292E"/>

    <!--窗体标题背景色-->
    <LinearGradientBrush x:Key="CaptionActiveBackgroundBrush"  EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#05AFA7" Offset="0.123456" />
        <GradientStop Color="#028ea1" Offset="0.987678" />
    </LinearGradientBrush>


    <!--版本背景色-->
    <LinearGradientBrush x:Key="VerBackgroundBrush" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#028ea1" Offset="0.123456" />
        <GradientStop Color="#05AFA7" Offset="0.987678" />
    </LinearGradientBrush>

    <!--窗体的背景颜色-->
    <LinearGradientBrush x:Key="WindowContentBackground" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#F5F5F7" Offset="0"/>
        <GradientStop Color="#FFFFFF" Offset="0.5"/>
        <GradientStop Color="#F5F5F7" Offset="1"/>
    </LinearGradientBrush>
    <!--最大化最小化按钮被按下-->
    <SolidColorBrush x:Key="CaptionButtonHighlightBorderBrush" Color="#D8DBE5"/>
    <!--标题字体颜色-->
    <SolidColorBrush x:Key="TitleForeground"  Color="#effff1"/>
    <!--版本字体颜色-->
    <SolidColorBrush x:Key="VerForeground"  Color="#effff1"/>
    <!--版本号的字体颜色-->
    <SolidColorBrush x:Key="VerCodeForeground" Color="#C32F86"/>
    <!--窗口边界颜色-->
    <SolidColorBrush x:Key="WindowBorderBrush" Color="#FFFFFF"/>
</ResourceDictionary>

Copy

WindowTemplate_Blue.xaml

代码语言:javascript复制
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sv="clr-namespace:WindowHelper">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/Supertek.WindowHelper;component/Themes/Svg/SvgImage.xaml"/>
        <ResourceDictionary Source="pack://application:,,,/Supertek.WindowHelper;component/Themes/Template/Blue.xaml"/>
        <ResourceDictionary Source="pack://application:,,,/Supertek.WindowHelper;component/Themes/Style/ButtonStyle.xaml"/>
        <ResourceDictionary Source="pack://application:,,,/Supertek.WindowHelper;component/Themes/Style/ResizeGripStyle.xaml"/>
        <ResourceDictionary Source="pack://application:,,,/Supertek.WindowHelper;component/Themes/Style/ThumbStyle.xaml"/>
        <ResourceDictionary Source="pack://application:,,,/Supertek.WindowHelper;component/Themes/Style/WindowStyle.xaml"/>
    </ResourceDictionary.MergedDictionaries>
    <Style x:Key="{x:Type sv:WindowBase}" TargetType="{x:Type sv:WindowBase}" BasedOn="{StaticResource StyleBase}"/>
</ResourceDictionary>

Copy

WindowTemplate_Cyan.xaml

代码语言:javascript复制
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sv="clr-namespace:Supertek.WindowHelper">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/Supertek.WindowHelper;component/Themes/Svg/SvgImage.xaml"/>
        <ResourceDictionary Source="pack://application:,,,/Supertek.WindowHelper;component/Themes/Template/Cyan.xaml"/>
        <ResourceDictionary Source="pack://application:,,,/Supertek.WindowHelper;component/Themes/Style/ButtonStyle.xaml"/>
        <ResourceDictionary Source="pack://application:,,,/Supertek.WindowHelper;component/Themes/Style/ResizeGripStyle.xaml"/>
        <ResourceDictionary Source="pack://application:,,,/Supertek.WindowHelper;component/Themes/Style/ThumbStyle.xaml"/>
        <ResourceDictionary Source="pack://application:,,,/Supertek.WindowHelper;component/Themes/Style/WindowStyle.xaml"/>
    </ResourceDictionary.MergedDictionaries>
    <Style x:Key="{x:Type sv:WindowBase}" TargetType="{x:Type sv:WindowBase}" BasedOn="{StaticResource StyleBase}"/>
</ResourceDictionary>

Copy

NativeMethods.cs

代码语言:javascript复制
using System;
using System.Security;
using System.ComponentModel;
using System.Windows.Controls;
using System.Runtime.InteropServices;

namespace WindowHelper
{
    internal static class NativeMethods
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct MINMAXINFO
        {
            public NativeMethods.POINT ptReserved;
            public NativeMethods.POINT ptMaxSize;
            public NativeMethods.POINT ptMaxPosition;
            public NativeMethods.POINT ptMinTrackSize;
            public NativeMethods.POINT ptMaxTrackSize;
        }

        [StructLayout(LayoutKind.Sequential)]
        public class POINT
        {
            public Int32 x;
            public Int32 y;
            public POINT()
            {
                x = y = 0;
            }
            public POINT(Int32 x, Int32 y)
            {
                this.x = x;
                this.y = y;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public Int32 left;
            public Int32 top;
            public Int32 right;
            public Int32 bottom;
            public RECT(Int32 left, Int32 top, Int32 right, Int32 bottom)
            {
                this.left = left;
                this.top = top;
                this.right = right;
                this.bottom = bottom;
            }
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public class MONITORINFO
        {
            public Int32 cbSize = Marshal.SizeOf(typeof(MONITORINFO));
            public RECT rcMonitor = new RECT();
            public RECT rcWork = new RECT();
            public Int32 dwFlags = 0;
        }

        /// <summary>When resizing a window, this is the side of the window being resized.</summary>
        public enum SizingWindowSide
        {
            /// <summary>WMSZ_LEFT: Left edge</summary>
            Left = 1,
            /// <summary>WMSZ_RIGHT: Right edge</summary>
            Right = 2,
            /// <summary>WMSZ_TOP: Top edge</summary>
            Top = 3,
            /// <summary>WMSZ_TOPLEFT: Top-left corner</summary>
            TopLeft = 4,
            /// <summary>WMSZ_TOPRIGHT: Top-right corner</summary>
            TopRight = 5,
            /// <summary>WMSZ_BOTTOM: Bottom edge</summary>
            Bottom = 6,
            /// <summary>WMSZ_BOTTOMLEFT: Bottom-left corner</summary>
            BottomLeft = 7,
            /// <summary>WMSZ_BOTTOMRIGHT: Bottom-right corner</summary>
            BottomRight = 8,
        }

        public enum HitTestResult
        {
            HTERROR = -2,
            HTTRANSPARENT = -1,
            HTNOWHERE = 0,
            HTCLIENT = 1,
            HTCAPTION = 2,
            HTSYSMENU = 3,
            HTGROWBOX = 4,
            HTSIZE = HTGROWBOX,
            HTMENU = 5,
            HTHSCROLL = 6,
            HTVSCROLL = 7,
            HTMINBUTTON = 8,
            HTMAXBUTTON = 9,
            HTLEFT = 10,
            HTRIGHT = 11,
            HTTOP = 12,
            HTTOPLEFT = 13,
            HTTOPRIGHT = 14,
            HTBOTTOM = 15,
            HTBOTTOMLEFT = 16,
            HTBOTTOMRIGHT = 17,
            HTBORDER = 18,
            HTREDUCE = HTMINBUTTON,
            HTZOOM = HTMAXBUTTON,
            HTSIZEFIRST = HTLEFT,
            HTSIZELAST = HTBOTTOMRIGHT,
            HTOBJECT = 19,
            HTCLOSE = 20,
            HTHELP = 21,
        }

        public const Int32 WM_MOVE = 0x0003;
        public const Int32 WM_SIZING = 0x0214;
        public const Int32 WM_NCHITTEST = 0x0084;
        public const Int32 WM_GETMINMAXINFO = 0x0024;
        public const Int32 MONITOR_DEFAULTTONEAREST = 0x0002;

        public static Int32 SignedLOWORD(IntPtr intPtr)
        {
            return (Int32)(intPtr.ToInt64() & 0xffff);
        }

        public static Int32 SignedHIWORD(IntPtr intPtr)
        {
            return (Int32)((intPtr.ToInt64() >> 16) & 0xffff);
        }

        [SecurityCritical]
        public static Object PtrToStructure(IntPtr lparam, Type clrType)
        {
            return Marshal.PtrToStructure(lparam, clrType);
        }

        [DllImport("user32.dll")]
        public static extern IntPtr MonitorFromWindow(IntPtr hwnd, Int32 dwFlags);

        [DllImport("user32.dll")]
        public static extern Boolean GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi);

        [DllImport("user32.dll")]
        public static extern IntPtr GetSystemMenu(IntPtr hwnd, Boolean bRevert);

        [DllImport("user32.dll")]
        public static extern Boolean SetMenu(IntPtr hwnd, IntPtr hMenu);

        [DllImport("user32.dll", EntryPoint = "GetClientRect", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
        private static extern Boolean IntGetClientRect(HandleRef hWnd, [In, Out] ref NativeMethods.RECT rect);
        [SecurityCritical, SecurityTreatAsSafe]
        public static void GetClientRect(HandleRef hWnd, [In, Out] ref NativeMethods.RECT rect)
        {
            if (!IntGetClientRect(hWnd, ref rect))
            {
                throw new Win32Exception();
            }
        }

        [SuppressUnmanagedCodeSecurity, SecurityCritical, DllImport("user32.dll", EntryPoint = "ClientToScreen", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
        private static extern Int32 IntClientToScreen(HandleRef hWnd, [In, Out] NativeMethods.POINT pt);
        [SecurityCritical]
        public static void ClientToScreen(HandleRef hWnd, [In, Out] NativeMethods.POINT pt)
        {
            if (IntClientToScreen(hWnd, pt) == 0)
            {
                throw new Win32Exception();
            }
        }
    }
}

Copy

WindowBase.cs

代码语言:javascript复制
using System;
using System.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Windows.Threading;
using System.Collections.Generic;

namespace WindowHelper
{
    public class WindowBase : Window
    {
        public static readonly DependencyProperty IsIconProperty = DependencyProperty.Register("IsIcon", typeof(bool), typeof(WindowBase), new UIPropertyMetadata(true));
        public static readonly DependencyProperty IsVerProperty = DependencyProperty.Register("IsVer", typeof(bool), typeof(WindowBase), new UIPropertyMetadata(true));
        public static readonly DependencyProperty IsMaxProperty = DependencyProperty.Register("IsMax", typeof(bool), typeof(WindowBase), new UIPropertyMetadata(true));
        public static readonly DependencyProperty IsMinProperty = DependencyProperty.Register("IsMin", typeof(bool), typeof(WindowBase), new UIPropertyMetadata(true));
        /// <summary>
        /// 是否需要显示图标
        /// </summary>
        public bool IsIcon
        {
            get { return (bool)this.GetValue(IsIconProperty); }
            set { this.SetValue(IsIconProperty, value); }
        }
        /// <summary>
        /// 是否需要显示版本号
        /// </summary>
        public bool IsVer
        {
            get { return (bool)this.GetValue(IsVerProperty); }
            set { this.SetValue(IsVerProperty, value); }
        }
        /// <summary>
        /// 是否需要显最大化按钮
        /// </summary>
        public bool IsMax
        {
            get { return (bool)this.GetValue(IsMaxProperty); }
            set { this.SetValue(IsMaxProperty, value); }
        }
        /// <summary>
        /// 是否需要显示最小化按钮
        /// </summary>
        public bool IsMin
        {
            get { return (bool)this.GetValue(IsMinProperty); }
            set { this.SetValue(IsMinProperty, value); }
        }





        private Button minimizeButton;
        private Button maximizeButton;
        private Button closeButton;
        private HwndSource currentHwndSource;
        private ContentControl windowIcon;
        private FrameworkElement moveGripper;
        private Label systemVer;
        private FrameworkElement ver;
        private Image icon;
        private Border caption;
        private Label captionText;


        private const string TopResizerName = "PART_TopResizer";
        private const string LeftResizerName = "PART_LeftResizer";
        private const string RightResizerName = "PART_RightResizer";
        private const string BottomResizerName = "PART_BottomResizer";
        private const string TopLeftResizerName = "PART_TopLeftResizer";
        private const string TopRightResizerName = "PART_TopRightResizer";
        private const string BottomLeftResizerName = "PART_BottomLeftResizer";
        private const string BottomRightResizerName = "PART_BottomRightResizer";
        private Thumb topResizer;
        private Thumb leftResizer;
        private Thumb rightResizer;
        private Thumb bottomResizer;
        private Thumb bottomRightResizer;
        private Thumb topRightResizer;
        private Thumb topLeftResizer;
        private Thumb bottomLeftResizer;

        public WindowBase()
        {
            //窗体最大化时不会覆盖任务栏
            WindowHelper.RepairWindowBehavior(this);
            MinHeight = 100;
            MinWidth = 100;
        }
        static WindowBase()
        {
            StyleProperty.OverrideMetadata(typeof(WindowBase), new FrameworkPropertyMetadata(null, new CoerceValueCallback(OnCoerceStyle)));
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WindowBase), new FrameworkPropertyMetadata(typeof(WindowBase)));
        }
        //加载样式
        static object OnCoerceStyle(DependencyObject d, object baseValue)
        {
            if (null == baseValue)
            {
                baseValue = (d as FrameworkElement).TryFindResource(typeof(WindowBase));
            }
            return baseValue;
        }
        //重写模板
        public override void OnApplyTemplate()
        {
            #region 暂不使用
            //caption = this.GetTemplateChild("PART_Caption") as Border;
            //caption.PreviewMouseLeftButtonDown  = new MouseButtonEventHandler(headerContainer_PreviewMouseLeftButtonDown);
            //caption.MouseLeftButtonDown  = new MouseButtonEventHandler(headerContainer_MouseLeftButtonDown);
            #endregion

            //CaptionText
            captionText= this.GetTemplateChild("CaptionText") as Label;
            minimizeButton = this.GetTemplateChild("PART_MinimizeButton") as Button;
            minimizeButton = this.GetTemplateChild("PART_MinimizeButton") as Button;
            maximizeButton = this.GetTemplateChild("PART_MaximizeButton") as Button;
            closeButton = this.GetTemplateChild("PART_CloseButton") as Button;
            windowIcon = this.GetTemplateChild("WindowIcon") as ContentControl;
            moveGripper = this.GetTemplateChild("WindowMoveGripper") as FrameworkElement;
            systemVer = this.GetTemplateChild("System_Ver") as Label;
            //版本号
            systemVer.Content = System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName).FileVersion;

            icon = this.GetTemplateChild("PART_Icon") as Image;
            if (!IsIcon)
            {
                icon.Visibility = Visibility.Collapsed;
            }

            ver = this.GetTemplateChild("PART_Ver") as FrameworkElement;
            if (!IsVer)
            {
                ver.Visibility = Visibility.Collapsed;
            }

            if (!IsMax)
            {
                maximizeButton.IsEnabled = false;
            }
            if (!IsMin)
            {
                minimizeButton.IsEnabled = false;
            }

            topResizer = this.GetTemplateChild(TopResizerName) as Thumb;
            topLeftResizer = GetTemplateChild(TopLeftResizerName) as Thumb;
            leftResizer = GetTemplateChild(LeftResizerName) as Thumb;
            rightResizer = GetTemplateChild(RightResizerName) as Thumb;
            bottomResizer = GetTemplateChild(BottomResizerName) as Thumb;
            bottomRightResizer = GetTemplateChild(BottomRightResizerName) as Thumb;
            topRightResizer = GetTemplateChild(TopRightResizerName) as Thumb;
            bottomLeftResizer = GetTemplateChild(BottomLeftResizerName) as Thumb;

            if (this.ResizeMode == ResizeMode.NoResize)
            {
                minimizeButton.Visibility = Visibility.Collapsed;
                maximizeButton.Visibility = Visibility.Collapsed;
                Grid.SetColumnSpan(captionText, 3);
                Grid.SetColumnSpan(moveGripper, 4);


                topResizer.Visibility = Visibility.Collapsed;
                topLeftResizer.Visibility = Visibility.Collapsed;
                leftResizer.Visibility = Visibility.Collapsed;
                rightResizer.Visibility = Visibility.Collapsed;
                bottomResizer.Visibility = Visibility.Collapsed;
                bottomRightResizer.Visibility = Visibility.Collapsed;
                topRightResizer.Visibility = Visibility.Collapsed;
                bottomLeftResizer.Visibility = Visibility.Collapsed;
            }
            else
            {
                topResizer.DragDelta  = new DragDeltaEventHandler(ResizeTop);
                topLeftResizer.DragDelta  = new DragDeltaEventHandler(ResizeTopLeft);
                leftResizer.DragDelta  = new DragDeltaEventHandler(ResizeLeft);
                rightResizer.DragDelta  = new DragDeltaEventHandler(ResizeRight);
                bottomResizer.DragDelta  = new DragDeltaEventHandler(ResizeBottom);
                bottomRightResizer.DragDelta  = new DragDeltaEventHandler(ResizeBottomRight);
                topRightResizer.DragDelta  = new DragDeltaEventHandler(ResizeTopRight);
                bottomLeftResizer.DragDelta  = new DragDeltaEventHandler(ResizeBottomLeft);
            }

            if (minimizeButton != null)
            {
                minimizeButton.Click  = OnWindowMinimizing;
            }
            if (maximizeButton != null)
            {
                maximizeButton.Click  = OnWindowStateRestoring;
            }
            if (closeButton != null)
            {
                closeButton.Click  = OnWindowClosing;
            }
            base.OnApplyTemplate();
        }

        //最大化与初始化
        private void OnWindowStateRestoring(Object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
            if (this.ResizeMode != ResizeMode.NoResize)
            {
                switch (WindowState)
                {
                    case WindowState.Normal:
                        topResizer.Visibility = Visibility.Visible;
                        topLeftResizer.Visibility = Visibility.Visible;
                        leftResizer.Visibility = Visibility.Visible;
                        rightResizer.Visibility = Visibility.Visible;
                        bottomResizer.Visibility = Visibility.Visible;
                        bottomRightResizer.Visibility = Visibility.Visible;
                        topRightResizer.Visibility = Visibility.Visible;
                        bottomLeftResizer.Visibility = Visibility.Visible;
                        break;
                    case WindowState.Maximized:
                        topResizer.Visibility = Visibility.Collapsed;
                        topLeftResizer.Visibility = Visibility.Collapsed;
                        leftResizer.Visibility = Visibility.Collapsed;
                        rightResizer.Visibility = Visibility.Collapsed;
                        bottomResizer.Visibility = Visibility.Collapsed;
                        bottomRightResizer.Visibility = Visibility.Collapsed;
                        topRightResizer.Visibility = Visibility.Collapsed;
                        bottomLeftResizer.Visibility = Visibility.Collapsed;
                        break;
                }
            }
        }
        //最小化
        private void OnWindowMinimizing(Object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }
        //关闭
        private void OnWindowClosing(Object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        #region 暂不使用

        ///// <summary>
        ///// 点击数量
        ///// </summary>
        //int CkickCount = 0;
        ///// <summary>
        ///// 双击检测
        ///// </summary>
        //private void headerContainer_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //      CkickCount;
        //    DispatcherTimer ClickTimer = new DispatcherTimer();
        //    ClickTimer.Interval = new TimeSpan(0, 0, 0, 0,100);
        //    ClickTimer.Tick  = (s, e1) =>
        //    {
        //        ClickTimer.IsEnabled = false;
        //        CkickCount = 0;
        //    };
        //    ClickTimer.IsEnabled = true;
        //    if (CkickCount % 2 == 0)
        //    {
        //        ClickTimer.IsEnabled = false;
        //        CkickCount = 0;

        //        if (this.WindowState == WindowState.Normal)
        //        {
        //            this.WindowState = WindowState.Maximized;
        //        }
        //        else
        //        {
        //            this.WindowState = WindowState.Normal;
        //        }
        //    }
        //}
        ///// <summary>
        ///// 单击移动
        ///// </summary>
        //private void headerContainer_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //    this.DragMove();
        //}
        #endregion

        #region 拖拽 右上-右-右下,下左-下-下右,左-左下

        private void ResizeBottomLeft(object sender, DragDeltaEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized) return;
            ResizeLeft(sender, e);
            ResizeBottom(sender, e);
        }

        private void ResizeTopLeft(object sender, DragDeltaEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized||this.ResizeMode==ResizeMode.NoResize) return;
            ResizeTop(sender, e);
            ResizeLeft(sender, e);
        }

        private void ResizeTopRight(object sender, DragDeltaEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized || this.ResizeMode == ResizeMode.NoResize) return;
            ResizeRight(sender, e);
            ResizeTop(sender, e);
        }

        private void ResizeBottomRight(object sender, DragDeltaEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized || this.ResizeMode == ResizeMode.NoResize) return;
            ResizeBottom(sender, e);
            ResizeRight(sender, e);
        }

        private void ResizeBottom(object sender, DragDeltaEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized || this.ResizeMode == ResizeMode.NoResize) return;
            if (ActualHeight <= MinHeight && e.VerticalChange < 0)
            {
                return;
            }
            if (double.IsNaN(Height))
            {
                Height = ActualHeight;
            }
            double num = Height;
            num  = e.VerticalChange;
            if (num > 0)
            {
                Height = num;
            }
        }

        private void ResizeRight(object sender, DragDeltaEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized || this.ResizeMode == ResizeMode.NoResize) return;
            if (ActualWidth <= MinWidth && e.HorizontalChange < 0)
            {
                return;
            }
            if (double.IsNaN(Width))
            {
                Width = ActualWidth;
            }
            double num = Width;
            num  = e.HorizontalChange;
            if (num > 0)
            {
                Width = num;
            }
        }

        private void ResizeLeft(object sender, DragDeltaEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized || this.ResizeMode == ResizeMode.NoResize) return;
            if (ActualWidth <= MinWidth && e.HorizontalChange > 0)
            {
                return;
            }
            if (double.IsNaN(Width))
            {
                Width = ActualWidth;
            }
            Width -= e.HorizontalChange;
            Left  = e.HorizontalChange;
        }

        private void ResizeTop(object sender, DragDeltaEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized || this.ResizeMode == ResizeMode.NoResize) return;
            if (ActualHeight <= MinHeight && e.VerticalChange > 0)
            {
                return;
            }
            if (double.IsNaN(Height))
            {
                Height = ActualHeight;
            }

            Console.WriteLine(e.VerticalChange);
            Height -= e.VerticalChange;
            Top  = e.VerticalChange;
        }

        #endregion

        #region 双击放大缩小  单击长按移动
        protected override void OnSourceInitialized(EventArgs e)
        {
            IntPtr currentHwnd = (new WindowInteropHelper(this)).Handle;
            currentHwndSource = HwndSource.FromHwnd(currentHwnd);
            currentHwndSource.AddHook(new HwndSourceHook(this.WinProc));
            base.OnSourceInitialized(e);
        }
        private IntPtr WinProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, ref Boolean handled)
        {
            IntPtr result = IntPtr.Zero;
            switch (msg)
            {
                case NativeMethods.WM_NCHITTEST:
                    handled = this.WmNcHitTest(lParam, ref result);
                    break;
            }
            return result;
        }

        private Boolean WmNcHitTest(IntPtr lParam, ref IntPtr result)
        {
            if (this.ResizeMode != ResizeMode.NoResize)
            {
                switch (WindowState)
                {
                    case WindowState.Normal:
                        topResizer.Visibility = Visibility.Visible;
                        topLeftResizer.Visibility = Visibility.Visible;
                        leftResizer.Visibility = Visibility.Visible;
                        rightResizer.Visibility = Visibility.Visible;
                        bottomResizer.Visibility = Visibility.Visible;
                        bottomRightResizer.Visibility = Visibility.Visible;
                        topRightResizer.Visibility = Visibility.Visible;
                        bottomLeftResizer.Visibility = Visibility.Visible;
                        break;
                    case WindowState.Maximized:
                        topResizer.Visibility = Visibility.Collapsed;
                        topLeftResizer.Visibility = Visibility.Collapsed;
                        leftResizer.Visibility = Visibility.Collapsed;
                        rightResizer.Visibility = Visibility.Collapsed;
                        bottomResizer.Visibility = Visibility.Collapsed;
                        bottomRightResizer.Visibility = Visibility.Collapsed;
                        topRightResizer.Visibility = Visibility.Collapsed;
                        bottomLeftResizer.Visibility = Visibility.Collapsed;
                        break;
                }
            }
            Int32 x = NativeMethods.SignedLOWORD(lParam);
            Int32 y = NativeMethods.SignedHIWORD(lParam);
            NativeMethods.POINT devicePoint = this.GetPointRelativeToWindow(x, y);
            Point logicalPoint = this.DeviceToLogicalUnits(new Point((Double)devicePoint.x, (Double)devicePoint.y));
            if (this.IsPointWithExtent(logicalPoint, this.windowIcon))
            {
                result = (IntPtr)NativeMethods.HitTestResult.HTSYSMENU;
                return true;
            }
            else if (this.IsPointWithExtent(logicalPoint, this.moveGripper))
            {
                result = (IntPtr)NativeMethods.HitTestResult.HTCAPTION;
                return true;
            }
            return false;
        }
        private Boolean IsPointWithExtent(Point point, FrameworkElement element)
        {
            if (element == null)
            {
                return false;
            }
            GeneralTransform transform = base.TransformToDescendant(element);
            Point resultPoint = point;
            if (transform != null && !transform.TryTransform(point, out resultPoint))
            {
                return false;
            }
            if (((resultPoint.X < 0) || (resultPoint.Y < 0)) || ((resultPoint.X > element.RenderSize.Width) || (resultPoint.Y > element.RenderSize.Height)))
            {
                return false;
            }

            return true;
        }
        private NativeMethods.POINT GetWindowScreenLocation(FlowDirection flowDirection)
        {
            NativeMethods.POINT point = new NativeMethods.POINT(0, 0);
            if (flowDirection == FlowDirection.RightToLeft)
            {
                NativeMethods.RECT rect = new NativeMethods.RECT(0, 0, 0, 0);
                NativeMethods.GetClientRect(new HandleRef(this, this.currentHwndSource.Handle), ref rect);
                point.x = rect.right;
                point.y = rect.top;
            }
            NativeMethods.ClientToScreen(new HandleRef(this, this.currentHwndSource.Handle), point);
            return point;
        }
        private NativeMethods.POINT GetPointRelativeToWindow(Int32 x, Int32 y)
        {
            NativeMethods.POINT point = this.GetWindowScreenLocation(base.FlowDirection);
            return new NativeMethods.POINT(x - point.x, y - point.y);
        }
        private Point DeviceToLogicalUnits(Point ptDeviceUnits)
        {
            return this.currentHwndSource.CompositionTarget.TransformFromDevice.Transform(ptDeviceUnits);
        }
        #endregion

    }
}

Copy

WindowHelper.cs

代码语言:javascript复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Media;
using System.Windows.Controls;
using System.Drawing;


namespace WindowHelper
{
    public static class WindowHelper
    {
        #region User32方法反射

        [StructLayout(LayoutKind.Sequential)]
        public struct MARGINS
        {
            public int cxLeftWidth;
            public int cxRightWidth;
            public int cyTopHeight;
            public int cyBottomHeight;
        };

        [DllImport("DwmApi.dll")]
        public static extern int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS pMarInset);

        [DllImport("user32")]
        internal static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi);
        [DllImport("User32")]
        internal static extern IntPtr MonitorFromWindow(IntPtr handle, int flags);

        [DllImport("user32.dll", EntryPoint = "GetClassLong")]
        private static extern uint GetClassLongPtr32(IntPtr hWnd, int nIndex);

        [DllImport("user32.dll", EntryPoint = "GetClassLongPtr")]
        [SuppressMessage("Microsoft.Interoperability", "CA1400")]
        private static extern IntPtr GetClassLongPtr64(IntPtr hWnd, int nIndex);

        [DllImport("user32.dll")]
        public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern IntPtr LoadImage(IntPtr hinst, IntPtr lpszName, uint uType, int cxDesired, int cyDesired, uint fuLoad);

        public static IntPtr GetClassLongPtr(IntPtr hWnd, int nIndex)
        {
            if (IntPtr.Size > 4)
            {
                return GetClassLongPtr64(hWnd, nIndex);
            }
            return new IntPtr((long)GetClassLongPtr32(hWnd, nIndex));
        }

        #endregion

        public static void RepairWindowBehavior(Window wpfWindow)
        {
            if (wpfWindow == null)
                return;
            wpfWindow.SourceInitialized  = delegate
            {
                IntPtr handle = (new WindowInteropHelper(wpfWindow)).Handle;
                HwndSource source = HwndSource.FromHwnd(handle);
                if (source != null)
                {
                    source.AddHook(WindowProc);
                }
            };
        }

        private static IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
                case 0x0024: WmGetMinMaxInfo(hwnd, lParam);
                    handled = true; break;
            }
            return (IntPtr)0;
        }

        private static void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam)
        {
            MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));
            int MONITOR_DEFAULTTONEAREST = 0x00000002;
            IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
            if (monitor != IntPtr.Zero)
            {
                MONITORINFO monitorInfo = new MONITORINFO(); GetMonitorInfo(monitor, monitorInfo);
                RECT rcWorkArea = monitorInfo.rcWork;
                RECT rcMonitorArea = monitorInfo.rcMonitor;
                mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
                mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
                mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);
                mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
            }
            Marshal.StructureToPtr(mmi, lParam, true);
        }

        #region Nested type: MINMAXINFO
        [StructLayout(LayoutKind.Sequential)]
        internal struct MINMAXINFO
        {
            public POINT ptReserved;
            public POINT ptMaxSize;
            public POINT ptMaxPosition;
            public POINT ptMinTrackSize;
            public POINT ptMaxTrackSize;
        }
        #endregion

        #region Nested type: MONITORINFO
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        internal class MONITORINFO
        {
            public int cbSize = Marshal.SizeOf(typeof(MONITORINFO));
            public RECT rcMonitor;
            public RECT rcWork;
            public int dwFlags;
        }
        #endregion

        #region Nested type: POINT
        [StructLayout(LayoutKind.Sequential)]
        internal struct POINT
        {
            public int x; public int y;
            public POINT(int x, int y) { this.x = x; this.y = y; }
        }
        #endregion

        #region Nested type: RECT
        [StructLayout(LayoutKind.Sequential, Pack = 0)]
        internal struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
            public static readonly RECT Empty;
            public int Width { get { return Math.Abs(right - left); } }
            public int Height { get { return bottom - top; } }
            public RECT(int left, int top, int right, int bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; }
            public RECT(RECT rcSrc) { left = rcSrc.left; top = rcSrc.top; right = rcSrc.right; bottom = rcSrc.bottom; }
            public bool IsEmpty { get { return left >= right || top >= bottom; } }
            public override string ToString()
            {
                if (this == Empty) { return "RECT {Empty}"; }
                return "RECT { left : "   left   " / top : "   top   " / right : "   right   " / bottom : "   bottom   " }";
            }
            public override bool Equals(object obj)
            {
                if (!(obj is Rect))
                {
                    return false;
                }
                return (this == (RECT)obj);
            }
            public override int GetHashCode()
            {
                return left.GetHashCode()   top.GetHashCode()   right.GetHashCode()   bottom.GetHashCode();
            }
            public static bool operator ==(RECT rect1, RECT rect2)
            {
                return (rect1.left == rect2.left && rect1.top == rect2.top && rect1.right == rect2.right && rect1.bottom == rect2.bottom);
            }
            public static bool operator !=(RECT rect1, RECT rect2) { return !(rect1 == rect2); }
        }
        #endregion

        public static void ExtendAeroGlass(Window window,IntPtr winHandle)
        {
            try
            {
                // 为WPF程序获取窗口句柄
                IntPtr mainWindowPtr = new WindowInteropHelper(window).Handle;
                HwndSource mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr);
                mainWindowSrc.CompositionTarget.BackgroundColor = Colors.Transparent;

                // 设置Margins
                MARGINS margins = new MARGINS();

                // Get the system DPI.
                System.Drawing.Graphics g = System.Drawing.
                Graphics.FromHwnd(winHandle);
                float desktopDpiX = g.DpiX;
                float desktopDpiY = g.DpiY;

                // 扩展Aero Glass
                margins.cxLeftWidth = Convert.ToInt32(5 * (desktopDpiX / 96));
                margins.cxRightWidth = Convert.ToInt32(5 * (desktopDpiX / 96));
                margins.cyTopHeight = Convert.ToInt32(window.Top * (desktopDpiX / 96));
                margins.cyBottomHeight = Convert.ToInt32(5 * (desktopDpiX / 96));



                int hr = DwmExtendFrameIntoClientArea(mainWindowSrc.Handle, ref margins);
                if (hr < 0)
                {
                    MessageBox.Show("DwmExtendFrameIntoClientArea Failed");
                }
            }
            catch (DllNotFoundException)
            {
                Application.Current.MainWindow.Background = System.Windows.Media.Brushes.White;
            }
        }

    }
}

Copy

MessageBox弹窗类

WindowMessageHelper.cs

代码语言:javascript复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using static WindowMessageHelper.WindowController;
using MessageBoxButton = WindowMessageHelper.WindowController.MessageBoxButton;

namespace WindowMessageHelper
{
    public class MessageBoxs
    {
        public static bool Show(string Content, string Title, MessageBoxButton btn, WindowController.MessageBoxImage img)
        {
            using (Window mainWindow = new Window())
            {
                ((WindowController)mainWindow.DataContext).SetMessage(Content, Title, btn, img);
                mainWindow.ShowDialog();
                return ((WindowController)mainWindow.DataContext).BoolRet;
            }
        }
    }
}

Copy

Style.xaml

代码语言:javascript复制
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">


    <Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Width" Value="100"/>
        <Setter Property="Height" Value="30"/>
        <Setter Property="Background" Value="#F7F7F7"/>
        <Setter Property="BorderBrush" Value="#C4C7CE"/>
        <Style.Triggers>
            <Trigger Property="IsFocused" Value="True"/>
        </Style.Triggers>
    </Style>
    <Style x:Key="ButtonStyle1" TargetType="{x:Type Button}" BasedOn="{StaticResource ButtonStyle}">
        <Setter Property="Width" Value="95"/>
    </Style>

    <Style x:Key="ButtonStyle2" TargetType="{x:Type Button}" BasedOn="{StaticResource ButtonStyle}">
        <Setter Property="Width" Value="80"/>
        <Setter Property="Height" Value="40"/>
    </Style>

    <Style x:Key="ButtonImageStyle" TargetType="{x:Type Image}">
        <Setter Property="Stretch" Value="Fill"/>
        <Setter Property="Margin" Value="0,0,5,0"/>
        <Setter Property="Width" Value="16"/>
        <Setter Property="Height" Value="16"/>
        <Setter Property="HorizontalAlignment" Value="Center"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
    </Style>
    <Style x:Key="ButtonImageStyle_Hede" TargetType="{x:Type Image}">
        <Setter Property="Stretch" Value="Fill"/>
        <Setter Property="Margin" Value="0,0,5,0"/>
        <Setter Property="Width" Value="20"/>
        <Setter Property="Height" Value="20"/>
        <Setter Property="HorizontalAlignment" Value="Center"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
    </Style>
    <Style x:Key="ButtonTextBlockStyle" TargetType="{x:Type TextBlock}">
        <Setter Property="FontSize" Value="13"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
        <Setter Property="Width" Value="auto"/>
        <Setter Property="Foreground" Value="{DynamicResource Font.Content.Foreground}"/>
    </Style>




    <!--自定义颜色-->
    <!-- 鼠标在按钮上方 背景色 -->
    <SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
    <!-- 鼠标在按钮上方 边框色 -->
    <SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
    <!-- 鼠标在按钮上方按下 背景色 -->
    <SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
    <!-- 鼠标在按钮上方按下 边框色 -->
    <SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
    <!--按钮失效 背景色-->
    <SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
    <!--按钮失效 边框色-->
    <SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
    <!--按钮失效 字体颜色-->
    <SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>

    <ControlTemplate x:Key="ButtonTemplate1" TargetType="{x:Type ButtonBase}">
        <Border x:Name="border" CornerRadius="3" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="true">
            <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="Button.IsDefaulted" Value="true">
                <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
            </Trigger>
            <Trigger Property="IsMouseOver" Value="true">
                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
            </Trigger>
            <Trigger Property="IsPressed" Value="true">
                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
            </Trigger>
            <Trigger Property="IsEnabled" Value="false">
                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
                <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
    <LinearGradientBrush x:Key="IsMouseOver_BackgroundBrushKey" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#FFFFFF" Offset="0" />
        <GradientStop Color="#E5F3FB" Offset="1" />
    </LinearGradientBrush>
    <SolidColorBrush x:Key="IsMouseOver_BorderBrushKey" Color="#70C0E7" />

    <!-- 按下状态的画刷 -->
    <LinearGradientBrush x:Key="IsPressed_BackgroundBrushKey" EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#FFFFFF" Offset="0" />
        <GradientStop Color="#D1E8FF" Offset="1" />
    </LinearGradientBrush>
    <SolidColorBrush x:Key="IsPressed_BorderBrushKey" Color="#66A7E8" />
    <!--END-->

    <Style x:Key="MenuButton" TargetType="{x:Type Button}" >
        <Setter Property="BorderBrush" Value="#E9ECF1"></Setter>
        <Setter Property="BorderThickness" Value="1"></Setter>
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="FontSize" Value="14"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"
                                SnapsToDevicePixels="true">
                        <ContentPresenter x:Name="contentPresenter"
                                              Focusable="False"
                                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                              Margin="{TemplateBinding Padding}"
                                              RecognizesAccessKey="True"
                                              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}"  />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="Border" Property="BorderBrush" Value="{StaticResource IsMouseOver_BorderBrushKey}" />
                            <Setter TargetName="Border" Property="Background" Value="{StaticResource IsMouseOver_BackgroundBrushKey}" />
                            <!--<Setter TargetName="Border" Property="BorderThickness" Value="0,1,0,1"/>-->
                        </Trigger>

                        <Trigger Property="IsPressed" Value="True">
                            <Setter TargetName="Border" Property="BorderBrush" Value="{StaticResource IsPressed_BorderBrushKey}" />
                            <Setter TargetName="Border" Property="Background" Value="{StaticResource IsPressed_BackgroundBrushKey}" />
                            <!--<Setter TargetName="Border" Property="BorderThickness" Value="0,1,0,1"/>-->
                        </Trigger>

                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

    </Style>


</ResourceDictionary>

Copy

Window.xaml

代码语言:javascript复制
<sv:WindowBase x:Class="WindowMessageHelper.Window"
        xmlns:sv="clr-namespace:WindowHelper;assembly=Supertek.WindowHelper"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  WindowStartupLocation="CenterScreen"
        xmlns:local="clr-namespace:WindowMessageHelper" IsVer="False" IsIcon="False" IsMax="False" IsMin="False"  Height="266" ResizeMode="NoResize"  MinWidth="266" Width="1">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Style.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <!--内容-->
        <Grid Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center"  Width="auto" >
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition Width="auto"/>
            </Grid.ColumnDefinitions>
            <Image Grid.Column="0" Source="{Binding IconImage}" Width="32"/>
            <Label Grid.Column="1" VerticalContentAlignment="Center"  FontSize="13"  HorizontalContentAlignment="Center" Content="{Binding Content_Info}" Name="ContentControl" Foreground="{DynamicResource Font.Content.Foreground}"/>
        </Grid>
        <!--版本-->
        <Border Grid.Row="2" BorderThickness="0,1,0,0"  Height="45" CornerRadius="{DynamicResource DownCornerRadius}"   Background="{StaticResource VerBackgroundBrush}">
            <Border.Effect>
                <DropShadowEffect BlurRadius="5" ShadowDepth="0" Opacity="0.3" />
            </Border.Effect>
            <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <Button  Template="{DynamicResource ButtonTemplate1}" Grid.Column="{Binding OkOrYes_GridColumn}" Grid.ColumnSpan="{Binding OkOrYes_GridColumnSpan}" Style="{StaticResource ButtonStyle}" Command="{Binding OkOrYes}"  Width="80" HorizontalAlignment="{Binding OkOrYes_HorizontalAlignment}" Margin="{Binding OkOrYes_Margin}">
                    <StackPanel Orientation="Horizontal">
                        <Image Source="{DynamicResource Confirm}" Style="{StaticResource ButtonImageStyle}"/>
                        <TextBlock Text="{Binding OkOrYes_Text}" Style="{StaticResource ButtonTextBlockStyle}"/>
                    </StackPanel>
                </Button>
                <Button  Template="{DynamicResource ButtonTemplate1}" Grid.Column="1" Style="{StaticResource ButtonStyle}" Command="{Binding CancelOrNo}"  Width="80" HorizontalAlignment="Left" Visibility="{Binding CancelOrNo_Visibility}" Margin="10,0,0,0">
                    <StackPanel Orientation="Horizontal">
                        <Image Source="{DynamicResource Cancel}" Style="{StaticResource ButtonImageStyle}"/>
                        <TextBlock Text="{Binding CancelOrNo_Text}" Style="{StaticResource ButtonTextBlockStyle}"/>
                    </StackPanel>
                </Button>
            </Grid>

        </Border>
    </Grid>
</sv:WindowBase>

Copy

WindowController.cs

代码语言:javascript复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows;
using Supertek.MvvmHelper;
using System.Windows.Controls;
using System.Drawing;
using System.Windows.Media.Imaging;
using Brushes = System.Windows.Media.Brushes;

namespace WindowMessageHelper
{
    public class WindowController : NotifyObject
    {
        public WindowController(FrameworkElement ThisWindow, Label ContentControl)
        {
            this.ContentControl = ContentControl;
            this.ThisWindow = (Window)ThisWindow;
        }
        /// <summary>
        /// 当前窗口
        /// </summary>
        public Window ThisWindow { get; set; }

        /// <summary>
        /// 图片资源
        /// </summary>
        public ImageSource IconImage
        {
            get
            {
                return iconImage;
            }
            set
            {
                if (!value.Equals(iconImage))
                {
                    iconImage = value;
                    RaisePropertyChanged("IconImage");
                }
            }
        }
        private ImageSource iconImage;
        /// <summary>
        /// 内容控件
        /// </summary>
        public Label ContentControl { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string Content_Info
        {
            get
            {
                return content_Info;
            }
            set
            {
                if (!value.Equals(content_Info))
                {
                    content_Info = value;
                    RaisePropertyChanged("Content_Info");
                }
            }
        }
        private string content_Info;



        /// <summary>
        /// 确认或是按钮在第几列
        /// </summary>
        public int OkOrYes_GridColumn
        {
            get
            {
                return okOrYes_GridColumn;
            }
            set
            {
                if (!value.Equals(okOrYes_GridColumn))
                {
                    okOrYes_GridColumn = value;
                    RaisePropertyChanged("OkOrYes_GridColumn");
                }
            }
        }
        private int okOrYes_GridColumn = 0;

        /// <summary>
        /// 确认或是按钮跨几行
        /// </summary>
        public int OkOrYes_GridColumnSpan
        {
            get
            {
                return okOrYes_GridColumnSpan;
            }
            set
            {
                if (!value.Equals(okOrYes_GridColumnSpan))
                {
                    okOrYes_GridColumnSpan = value;
                    RaisePropertyChanged("OkOrYes_GridColumnSpan");
                }
            }
        }
        private int okOrYes_GridColumnSpan = 1;
        /// <summary>
        /// 确认或是按钮 靠左、靠右、居中
        /// </summary>
        public HorizontalAlignment OkOrYes_HorizontalAlignment
        {
            get
            {
                return okOrYes_HorizontalAlignment;
            }
            set
            {
                if (!value.Equals(okOrYes_HorizontalAlignment))
                {
                    okOrYes_HorizontalAlignment = value;
                    RaisePropertyChanged("OkOrYes_HorizontalAlignment");
                }
            }
        }
        private HorizontalAlignment okOrYes_HorizontalAlignment = HorizontalAlignment.Center;  //默认居中
        /// <summary>
        /// 确认或是按钮 边距
        /// </summary>
        public Thickness OkOrYes_Margin
        {
            get
            {
                return okOrYes_Margin;
            }
            set
            {
                if (!value.Equals(okOrYes_Margin))
                {
                    okOrYes_Margin = value;
                    RaisePropertyChanged("OkOrYes_Margin");
                }
            }
        }
        private Thickness okOrYes_Margin = new Thickness(0);
        /// <summary>
        /// 确认或是按钮 显示的内容
        /// </summary>
        public string OkOrYes_Text
        {
            get
            {
                return okOrYes_Text;
            }
            set
            {
                if (!value.Equals(okOrYes_Text))
                {
                    okOrYes_Text = value;
                    RaisePropertyChanged("OkOrYes_Text");
                }
            }
        }
        private string okOrYes_Text;
        /// <summary>
        /// 确认或是按钮点击
        /// </summary>
        public Command OkOrYes
        {
            get
            {
                if (okOrYes == null)
                    okOrYes = new Command(new Action<object>
                    (
                        o =>
                        {
                            BoolRet = true;
                            ThisWindow.Close();
                        }
                    ));
                return okOrYes;
            }
        }
        private Command okOrYes;
        /// <summary>
        /// 取消或否按钮点击
        /// </summary>
        public Command CancelOrNo
        {
            get
            {
                if (cancelOrNo == null)
                    cancelOrNo = new Command(new Action<object>
                    (
                        o =>
                        {
                            BoolRet = false;
                            ThisWindow.Close();
                        }
                    ));
                return cancelOrNo;
            }
        }
        private Command cancelOrNo;

        /// <summary>
        /// 取消或否按钮 显示隐藏
        /// </summary>
        public Visibility CancelOrNo_Visibility
        {
            get
            {
                return cancelOrNo_Visibility;
            }
            set
            {
                if (!value.Equals(cancelOrNo_Visibility))
                {
                    cancelOrNo_Visibility = value;
                    RaisePropertyChanged("CancelOrNo_Visibility");
                }
            }
        }
        private Visibility cancelOrNo_Visibility;

        /// <summary>
        /// 确认或是按钮 显示的内容
        /// </summary>
        public string CancelOrNo_Text
        {
            get
            {
                return cancelOrNo_Text;
            }
            set
            {
                if (!value.Equals(cancelOrNo_Text))
                {
                    cancelOrNo_Text = value;
                    RaisePropertyChanged("CancelOrNo_Text");
                }
            }
        }
        private string cancelOrNo_Text;

        /// <summary>
        /// 设置消息
        /// </summary>
        /// <param name="Content">内容</param>
        /// <param name="Title">提示文本框</param>
        /// <param name="btn">按钮</param>
        /// <param name="img">图标</param>
        /// <returns></returns>
        public bool SetMessage(string Content, string Title, MessageBoxButton btn, MessageBoxImage img)
        {
            switch (btn)
            {
                case MessageBoxButton.OK:
                    OkOrYes_GridColumn = 0;
                    OkOrYes_GridColumnSpan = 2;
                    OkOrYes_HorizontalAlignment = HorizontalAlignment.Center;
                    OkOrYes_Margin = new Thickness(0);
                    OkOrYes_Text = "确认";
                    CancelOrNo_Visibility = Visibility.Collapsed;
                    break;
                case MessageBoxButton.OKCancel:
                    OkOrYes_GridColumn = 0;
                    OkOrYes_GridColumnSpan = 1;
                    OkOrYes_HorizontalAlignment = HorizontalAlignment.Right;
                    OkOrYes_Margin = new Thickness(0, 0, 10, 0);
                    OkOrYes_Text = "确认";
                    CancelOrNo_Text = "取消";
                    CancelOrNo_Visibility = Visibility.Visible;
                    break;
                case MessageBoxButton.Yes:
                    OkOrYes_GridColumn = 0;
                    OkOrYes_GridColumnSpan = 2;
                    OkOrYes_HorizontalAlignment = HorizontalAlignment.Center;
                    OkOrYes_Margin = new Thickness(0);
                    OkOrYes_Text = "是";
                    CancelOrNo_Visibility = Visibility.Collapsed;
                    break;
                case MessageBoxButton.YesNo:
                    OkOrYes_GridColumn = 0;
                    OkOrYes_GridColumnSpan = 1;
                    OkOrYes_HorizontalAlignment = HorizontalAlignment.Right;
                    OkOrYes_Margin = new Thickness(0, 0, 10, 0);
                    OkOrYes_Text = "是";
                    CancelOrNo_Text = "否";
                    CancelOrNo_Visibility = Visibility.Visible;
                    break;
            }
            switch (img)
            {
                case MessageBoxImage.Exclamation:
                    IconImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(new Icon(SystemIcons.Exclamation, 32, 32).Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                    break;
                case MessageBoxImage.Application:
                    IconImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(new Icon(SystemIcons.Application, 32,32).Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                    break;
                case MessageBoxImage.Asterisk:
                    IconImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(new Icon(SystemIcons.Asterisk, 32,32).Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                    break;
                case MessageBoxImage.Error:
                    IconImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(new Icon(SystemIcons.Error, 32,32).Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                    break;
                case MessageBoxImage.Hand:
                    IconImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(new Icon(SystemIcons.Hand, 32,32).Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                    break;
                case MessageBoxImage.Information:
                    IconImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(new Icon(SystemIcons.Information, 32,32).Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                    break;
                case MessageBoxImage.Question:
                    IconImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(new Icon(SystemIcons.Question, 32,32).Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                    break;
                case MessageBoxImage.Shield:
                    IconImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(new Icon(SystemIcons.Shield, 32,32).Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                    break;
                case MessageBoxImage.Warning:
                    IconImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(new Icon(SystemIcons.Warning, 32,32).Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                    break;
                case MessageBoxImage.WinLogo:
                    IconImage = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(new Icon(SystemIcons.WinLogo, 32,32).Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                    break;
            }

            Content_Info = Content;

            ThisWindow.Title = Title;

            ThisWindow.Width  = MeasureTextWidth(Content, 13, "Microsoft YaHei UI")  140;

            return true;
        }
        public enum MessageBoxButton
        {
            /// <summary>
            /// 确认按钮
            /// </summary>
            OK = 0,
            /// <summary>
            /// 确认取消按钮
            /// </summary>
            OKCancel = 1,
            /// <summary>
            /// 是按钮
            /// </summary>
            Yes = 2,
            /// <summary>
            /// 是否按钮
            /// </summary>
            YesNo = 3
        }


        public enum MessageBoxImage
        {
            /// <summary>
            /// 黄色背景/三角形/黑色感叹高
            /// </summary>
            Exclamation,
            /// <summary>
            /// 应用程序图标
            /// </summary>
            Application,
            /// <summary>
            /// 蓝色背景/圆形/白色倒立感叹号
            /// </summary>
            Asterisk,
            /// <summary>
            /// 红色背景/圆形/白色差
            /// </summary>
            Error,
            /// <summary>
            /// 红色背景/圆形/白色差
            /// </summary>
            Hand,
            /// <summary>
            /// 蓝色背景/圆形/白色倒立感叹号
            /// </summary>
            Information,
            /// <summary>
            /// 蓝色背景/圆形/白色问号
            /// </summary>
            Question,
            /// <summary>
            /// 盾牌
            /// </summary>
            Shield,
            /// <summary>
            /// 黄色背景/三角形/黑色感叹高
            /// </summary>
            Warning,
            /// <summary>
            /// 应用程序图标
            /// </summary>
            WinLogo
        }

        /// <summary>
        /// 计算字符串长度,设置控件长度
        /// </summary>
        /// <param name="text"></param>
        /// <param name="fontSize"></param>
        /// <param name="fontFamily"></param>
        /// <returns></returns>
        private double MeasureTextWidth(string text, double fontSize, string fontFamily)
        {
            return new FormattedText(text, System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface(fontFamily.ToString()), fontSize, Brushes.Black).WidthIncludingTrailingWhitespace;
        }

        /// <summary>
        /// 返回状态
        /// </summary>
        public bool BoolRet { get; set; }
    }
}

Copy

MVVM模式扩展方法

命令 Command .cs

代码语言:javascript复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Mvvmhelper
{
    /// <summary>
    /// 命令
    /// </summary>
    public class Command : ICommand
    {
        /// <summary>
        /// 检查命令是否可以执行的事件,在UI事件发生导致控件状态或数据发生变化时触发
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (_canExecute != null)
                {
                    CommandManager.RequerySuggested  = value;
                }
            }
            remove
            {
                if (_canExecute != null)
                {
                    CommandManager.RequerySuggested -= value;
                }
            }
        }

        /// <summary>
        /// 判断命令是否可以执行的方法
        /// </summary>
        private Func<object, bool> _canExecute;

        /// <summary>
        /// 命令需要执行的方法
        /// </summary>
        private Action<object> _execute;

        /// <summary>
        /// 创建一个命令
        /// </summary>
        /// <param name="execute">命令要执行的方法</param>
        public Command(Action<object> execute) : this(execute, null)
        {
        }

        /// <summary>
        /// 创建一个命令
        /// </summary>
        /// <param name="execute">命令要执行的方法</param>
        /// <param name="canExecute">判断命令是否能够执行的方法</param>
        public Command(Action<object> execute, Func<object, bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        /// <summary>
        /// 判断命令是否可以执行
        /// </summary>
        /// <param name="parameter">命令传入的参数</param>
        /// <returns>是否可以执行</returns>
        public bool CanExecute(object parameter)
        {
            if (_canExecute == null) return true;
            return _canExecute(parameter);
        }

        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="parameter"></param>
        public void Execute(object parameter)
        {
            if (_execute != null && CanExecute(parameter))
            {
                _execute(parameter);
            }
        }
    }

    public class Command<T> : ICommand
    {
        /// <summary>
        /// 检查命令是否可以执行的事件,在UI事件发生导致控件状态或数据发生变化时触发
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (_canExecute != null)
                {
                    CommandManager.RequerySuggested  = value;
                }
            }
            remove
            {
                if (_canExecute != null)
                {
                    CommandManager.RequerySuggested -= value;
                }
            }
        }

        /// <summary>
        /// 判断命令是否可以执行的方法
        /// </summary>
        private Func<T, bool> _canExecute;

        /// <summary>
        /// 命令需要执行的方法
        /// </summary>
        private Action<T> _execute;

        /// <summary>
        /// 创建一个命令
        /// </summary>
        /// <param name="execute">命令要执行的方法</param>
        public Command(Action<T> execute) : this(execute, null)
        {
        }

        /// <summary>
        /// 创建一个命令
        /// </summary>
        /// <param name="execute">命令要执行的方法</param>
        /// <param name="canExecute">判断命令是否能够执行的方法</param>
        public Command(Action<T> execute, Func<T, bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        /// <summary>
        /// 判断命令是否可以执行
        /// </summary>
        /// <param name="parameter">命令传入的参数</param>
        /// <returns>是否可以执行</returns>
        public bool CanExecute(object parameter)
        {
            if (_canExecute == null) return true;
            return _canExecute((T)parameter);
        }

        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="parameter"></param>
        public void Execute(object parameter)
        {
            if (_execute != null && CanExecute(parameter))
            {
                _execute((T)parameter);
            }
        }
    }
}

Copy

事件命令 EventCommand.cs

代码语言:javascript复制
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace Mvvmhelper
{
    /// <summary>
    /// 事件命令   需要到nuget 安装 System.Windows.Interactivity
    /// </summary>
    public class EventCommand : TriggerAction<DependencyObject>
    {

        /// <summary>
        /// 事件要绑定的命令
        /// </summary>
        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MsgName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register("Command", typeof(ICommand), typeof(EventCommand), new PropertyMetadata(null));

        /// <summary>
        /// 绑定命令的参数,保持为空就是事件的参数
        /// </summary>
        public object CommandParateter
        {
            get { return (object)GetValue(CommandParateterProperty); }
            set { SetValue(CommandParateterProperty, value); }
        }

        // Using a DependencyProperty as the backing store for CommandParateter.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CommandParateterProperty =
            DependencyProperty.Register("CommandParateter", typeof(object), typeof(EventCommand), new PropertyMetadata(null));

        //执行事件
        protected override void Invoke(object parameter)
        {
            if (CommandParateter != null)
                parameter = CommandParateter;
            var cmd = Command;
            if (cmd != null)
                cmd.Execute(parameter);
        }
    }
}

Copy

通知 NotifyObject.cs

代码语言:javascript复制
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mvvmhelper
{
    /// <summary>
    /// 通知对象
    /// </summary>
    public class NotifyObject : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;
        /// <summary>
        /// 属性发生改变时调用该方法发出通知
        /// </summary>
        /// <param name="propertyName">属性名称</param>
        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected virtual void SetAndNotifyIfChanged<T>(string propertyName, ref T oldValue, T newValue)
        {
            if (oldValue == null && newValue == null) return;
            if (oldValue != null && oldValue.Equals(newValue)) return;
            if (newValue != null && newValue.Equals(oldValue)) return;
            oldValue = newValue;
            RaisePropertyChanged(propertyName);
        }
    }
}

Copy

关键的地方来了,使用方式

1.创建一个解决方案,选中WPF窗口

2.到App.xaml中引用一个默认的资源模板

代码语言:javascript复制
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/WindowHelper;component/Themes/WindowTemplate_Blue.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Copy

3.定义几个单选按钮,哪个选中就使用哪个资源

代码语言:javascript复制
//切换模板
Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart)(() =>
               {
                   string strSourceDic = "pack://application:,,,/WindowHelper;component/Themes/WindowTemplate_"   rdb.Tag.ToString()   ".xaml";
                   Application.Current.Resources.BeginInit();
                   Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary()
                   {
                       Source = new Uri(strSourceDic, UriKind.RelativeOrAbsolute)
                   });
                   Application.Current.Resources.MergedDictionaries.RemoveAt(0);
                   Application.Current.Resources.EndInit();

               }));

Copy

4.图片资源的使用已在最开始说过了,请往上翻,自行查看

所有代码及使用方式都已分享,喜欢的话可以点赞收藏赞助哦

“关注[顺网]微信公众号,了解更多更有趣的实时信息”

本文作者:[博主]大顺

本文链接:https://shunnet.top/mInmmq

版权声明:转载注明出处,谢谢

0 人点赞