山東政務(wù)網(wǎng)站建設(shè)seo和sem的聯(lián)系
上周在看別人寫的上位機demo代碼時,發(fā)現(xiàn)創(chuàng)建的項目模板是"Windows 窗體控件庫"(如下圖)
?生成的項目結(jié)構(gòu)像自定義控件庫,沒有程序入口方法Main,但卻很神奇能調(diào)試,最后發(fā)現(xiàn)原來Vistual Studio啟動了一個外掛程序UserControl TestContainer.exe,運行效果如下圖:
?最后發(fā)現(xiàn)該exe在目錄C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE下,這個目錄和安裝的vistual studio的版本有關(guān),如下圖:
通過反編譯看到了PropertyGrid控件,如下圖,然后查閱相關(guān)的博客就知道怎樣使用了
?
而最近發(fā)現(xiàn)我們公司的項目發(fā)現(xiàn)也用到了該控件,所以學(xué)習(xí)它就提上了日程。像有些卡業(yè)務(wù)流程或者調(diào)用第三方的接口的業(yè)務(wù)邏輯,某些機器因某種原因需要臨時關(guān)閉該功能,就可以使用該控件實現(xiàn)個性化控制了,我上一家公司是用一個表來存儲這種個性化設(shè)置參數(shù),這樣就要向數(shù)據(jù)庫中查詢一次,有點浪費性能了。
好了,下面就和我一起體驗一下該控件吧,當然網(wǎng)上也有很多博客教程了,本文就簡單意思一下就行,核心就是設(shè)置PropertyGrid控件的SelectedObject屬性為對應(yīng)的Control控件
步驟如下:
1? 新增winfrom項目,項目名稱為:UserControlContainer,生成的項目結(jié)構(gòu)默認有一個Form1,就用它了
2? 在工具箱中向Form1窗體拖入Button、Panel和PropertyGrid控件,布局如下:
?
3 新增自定義控件,名為:UserControlTest,如下圖:
詳細代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace UserControlContainer
{public partial class UserControlTest : UserControl{private string _newProp;[Browsable(true), Category("自定義屬性"), Description("測試描述")]public string NewProp{get { return _newProp; }set { this._newProp = value; }}public UserControlTest(){InitializeComponent();}}
}
代碼中添加了自定義屬性NewProp,屬性上的標記信息用于程序在運行時顯示的屬性信息
4? 在Form1編寫的代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace UserControlContainer
{public partial class Form1 : Form{UserControlTest userControlTest;public Form1(){InitializeComponent();button1.Click += button1_Click;button2.Click += Button2_Click;button3.Click += Button3_Click;userControlTest = new UserControlTest();userControlTest.Dock = DockStyle.Fill;userControlTest.BackColor = Color.Black;this.panel1.Controls.Add(userControlTest);}/// <summary>/// 鼠標點擊事件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button1_Click(object sender, EventArgs e){this.propertyGrid1.SelectedObject = this.button1;}/// <summary>/// 設(shè)為空按鈕點擊事件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button2_Click(object sender, EventArgs e){this.propertyGrid1.SelectedObject = null;}private void Button3_Click(object sender, EventArgs e){this.propertyGrid1.SelectedObject = this.userControlTest;}}
}
代碼太簡單了,就不解釋了
5? 運行測試效果如下圖:
剛啟動的效果圖:
點擊"設(shè)置按鈕",按鈕,可以看到右邊的屬性框信息,如下圖:
?
通過右邊的屬性框 修改"設(shè)置按鈕"的按鈕名稱為"設(shè)置按鈕123",效果如下圖:
?
點擊"設(shè)為空"按鈕,效果如下圖:
點擊"設(shè)置自定義控件"按鈕,可以看到自定義的屬性NewProp,效果如下圖:
?
?然后在右邊的屬性框中修改自定義控件的背景顏色為紅色,效果如下圖:
好了,本文到此結(jié)束。
?
?