WPF自定义Window样式(2)

目录:

 WPF自定义Window样式(1)

 WPF自定义Window样式(2)

 

1. 引言

  在上一篇中,介绍了如何建立自定义窗体。接下来,我们需要考虑将该自定义窗体基类放到类库中去,只有放到类库中,我们才能在其他地方去方便的引用该基类。

2. 创建类库

  接上一篇的项目,先添加一个类库项目stonemqy.CustomWindow.Helpers。理所当然的,我们接下来需要把VisualStates、TransitioningContentControl、CustomWindow、Themes/Generic.xaml等文件放入类库中。此时,要注意添加如下引用:

    PresentationCor(4.0.0.0)

    PresentationFramework(4.0.0.0)

    Microsoft.Expression.Interactions(4.5.0.0)

    System.Windows.Interactivity(4.5.0.0)

    System.Xaml(4.0.0.0)

    WindowBase(4.0.0.0)

  此时,我们发现仍然不能添加资源文件。还需要用记事本打开项目文件stonemqy.CustomWindow.Helpers.csproj,在第一个PropertyGroup节中手动添加如下代码,这行代码允许在类库中添加WPF窗体及资源字典等文件。

<PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{07AAB444-6AD3-469D-9E94-4A84BADFB36D}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>stonemqy.CustomWindow.Helpers</RootNamespace>
    <AssemblyName>stonemqy.CustomWindow.Helpers</AssemblyName>
    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
  </PropertyGroup>

 

  注意要把Generic.xaml文件中的local引用修改一下:

xmlns:local="clr-namespace:stonemqy.CustomWindow.Helpers"

  至此,我们就完成了建立类库项目的工作。

3. 在主项目中引用类库

  修改主项目的MainWindow.xaml,同时修改MainWindow.cs中CustomWindow的命名空间。

<local:CustomWindow x:Class="stonemqy.CustomWindow.Main.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:stonemqy.CustomWindow.Helpers;assembly=stonemqy.CustomWindow.Helpers"
        Title="MainWindow-In Lib" Height="350" Width="525" Icon="logo.png">
    <Grid>
        
    </Grid>
</local:CustomWindow>
public partial class MainWindow : Helpers.CustomWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

  迫不及待的看看运行效果吧

  

  怎么回事儿?!!程序并没有启用自定义样式。又是一番鸡飞狗跳……

4. 使用类库中自定义窗体基类样式

  一番Google、CodeProject、StackOverflow后,终于找到了原因, 需要在Helpers项目中AssemblyInfo.cs中添加如下一行代码:

[assembly:ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]

  再运行一次程序,熟悉的自定义窗体又出来了:

5. 源码

源码

posted @ 2018-01-11 16:54  stonemqy  阅读(1782)  评论(6编辑  收藏  举报