本章讲述:WPF 控制台程序/Window应用程序转换为类库的方法步骤;
新建项目“WPF_WindowToDll”,在MainWindow.xaml中添加代码:
<Window x:Class="WPF_WindowToDll.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="525">
<StackPanel Margin="10">
<Button Margin="10" Width="120" Height="40" Content="WPF_WindowToDll"/>
<Button Margin="10" Width="120" Height="40" Content="WPF_WindowToDll"/>
<Button Margin="10" Width="120" Height="40" Content="WPF_WindowToDll"/>
<Button Margin="10" Width="120" Height="40" Content="WPF_WindowToDll"/>
</StackPanel>
</Window>
WPF控制台应用程序要转换成类库,只需要将项目的输出类型更改为类库,如下图:
但是,当重新编译项目的时候,你会发现事情没有那么简单,报错了,如下图:
要解决这个问题有两种方法:
方法一:
1、将项目的输出类型更改为类库;
2、直接把项目中的“App.xaml”,然后重新编译;
方法二:
1、将项目的输出类型更改为类库;
2、更改 App.xaml 文件属性,把“生成操作”设置为“无”,重新生成项目即可,如图下图所示
添加新项目“WPF_WindowToDllTest”,在该项目引用该Dll,添加类库到工程,添加后效果如下图:
在“MainWindow.cs”中,调用dll库界面,简单的调用示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPF_WindowToDll;
namespace WPF_WindowToDllTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
WPF_WindowToDll.MainWindow view = new WPF_WindowToDll.MainWindow();
view.ShowDialog();
}
}
}
运行结果图: