目錄:
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. 源碼