WPF添加類庫並引用


源碼地址:https://github.com/lizhiqiang0204/-WpfApp2.git

首先利用WPF向導創建一個空的項目

using System.Windows;

namespace WpfApp2
{
    /// <summary>
    /// MainWindow.xaml 的交互邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}
<Window x:Class="WpfApp2.MainWindow"
        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"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        
    </Grid>
</Window>

右擊解決方案->添加->新建項

找到類庫(.NET Framework)(我這個VS是2019,不同版本的VS這個添加界面有所不同)

然后點擊下一步,創建

把生成的Class1.cs修改一下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibrary1
{
    public class Calculate
    {
        public int sum(int a, int b)//
        {
            return a + b;
        }

        public int sub(int a, int b)//
        {
            return a - b;
        }
    }
}

右擊ClassLibrary1項目,生成庫文件DLL

生成成功后,后顯示已生成dll文件,此時MainWindow.xaml.cs就可以引用這個庫文件了

修改MainWindow.xaml.cs文件如下:

using ClassLibrary1;//引用自己創建的類庫
using System.Windows;

namespace WpfApp2
{
    /// <summary>
    /// MainWindow.xaml 的交互邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        Calculate calculate = new Calculate();//實例化類庫里的類
        int sum = 0;
        public MainWindow()
        {
            InitializeComponent();
            sum = calculate.sum(1, 2);
            MessageBox.Show("算術和為:" + sum.ToString());
        }
    }
}

運行結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM