讓Winform披上CSS的外衣

來源:互聯網
上載者:User
運行期改變Winform的外觀,讓Winform可以像Asp.Net一樣,通過類似CSS一樣的設定檔實現外觀的自訂。
當然,設定檔是XML格式的,而不是CSS格式的。
怎樣才能實現呢?
總共分三步,下面我們一步一步來。
第一步:建立一個用來儲存外觀屬性的對象,這裡我把它定義為Style.cs。

protected Color m_TextBackColor = Color.Yellow;

protected Color m_TextForeColor = Color.Blue;

protected Font m_TextFont = new System.Drawing.Font("宋體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));

public string XMLTextBackColor
{
    get { return cc.ConvertToString(m_TextBackColor); }
    set { m_TextBackColor = (Color)cc.ConvertFromString(value); }
}

public string XMLTextForeColor
{
    get { return cc.ConvertToString(m_TextForeColor); }
    set { m_TextForeColor = (Color)cc.ConvertFromString(value); }
}

public string XMLTextFont
{
    get { return fc.ConvertToString(m_TextFont); }
    set { m_TextFont = (Font)fc.ConvertFromString(value); }
}

[XmlIgnore]
public Color TextBackColor
{
    get { return m_TextBackColor; }
    set { m_TextBackColor = value; }
}

[XmlIgnore]
public Color TextForeColor
{
    get { return m_TextForeColor; }
    set { m_TextForeColor = value; }
}


[XmlIgnore]
public Font TextFont
{
    get { return m_TextFont; }
    set { m_TextFont = value; }
}

這個類裡面都是類似這樣的一些顏色字型之類的外觀,注意,這裡面有兩類屬性,一類(以XML開頭)是跟XML設定檔關聯的,另一類是為了防止設定檔裡面沒有定義,就採用預設值。

第二步:在表單上添加一個BindingSource控制項,並且按照設定屬性。
設定好了DataSource之後,我們最後需要做的就是把這兩個東西和我們所說的設定檔真正的聯絡起來。

進入第三步:產生XML檔案,並且利用這個檔案。
.Net的System.Xml.Serialization空間裡面的一些類可以協助我們。
我們需要讀寫設定檔、序列化和還原序列化Style類,那麼我們就要用到XmlTextReader、XmlSerializer兩個類。XmlTextReader xr = null;
xr = new XmlTextReader(filePath);
xr.WhitespaceHandling = WhitespaceHandling.All;
XmlSerializer serializer = new XmlSerializer(typeof(Style));
m_Style = (Style)serializer.Deserialize(xr);
return m_Style;

XmlSerializer serializer = null;
FileStream ioStream = null;
Style style = new Style();
serializer = new XmlSerializer(typeof(Style));
ioStream = new FileStream(filePath, FileMode.Create);
serializer.Serialize(ioStream, style);

以上分別是讀取設定檔然後把設定檔還原序列化和序列化到設定檔的操作。
這樣子,我們就可以利用設定檔了。
只需要在表單的構造方法中把BindingSource的DataSource設定為利用XML檔案還原序列化的類的執行個體就可以了。
完整的代碼:http://files.cnblogs.com/game-over/StyleForm.zip
最後貼一張:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.