轉(zhuǎn)帖|其它|編輯:郝浩|2011-09-15 14:04:47.000|閱讀 1421 次
概述:C# WinForm控件開發(fā)設(shè)置默認(rèn)值是非常有必要的,實(shí)現(xiàn)起來也很容易,本文筆者為你介紹設(shè)置默認(rèn)值的方法,希望能給你帶來幫助。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
C# WinForm控件開發(fā)設(shè)置默認(rèn)值是非常有必要的,實(shí)現(xiàn)起來也很容易,本文筆者為你介紹設(shè)置默認(rèn)值的方法,希望能給你帶來幫助。
如果你為屬性設(shè)定了默認(rèn)值,那么當(dāng)開發(fā)者修改了屬性的值,這個(gè)值在Property Explorer中將會(huì)以粗體顯示。VS為屬性提供一個(gè)上下文菜單,允許程序員使用C# WinForm控件開發(fā)把值重置為默認(rèn)值。
當(dāng)Visual Studio進(jìn)行控件的串行化時(shí),他會(huì)判斷那些值不是默認(rèn)值,只有不是設(shè)置默認(rèn)值的屬性才會(huì)被串行化,所以為屬性提供設(shè)置默認(rèn)值時(shí)可以大大減少串行化的屬性數(shù)目,提高效率。
那么Visual Studio進(jìn)怎么知道我們的屬性值不是默認(rèn)值了呢?我們需要一種機(jī)制來通知Visual Studio進(jìn)默認(rèn)值。實(shí)現(xiàn)這種機(jī)制有兩種方法:
對(duì)于簡(jiǎn)單類型的屬性,比如Int32,Boolean等等這些Primitive類型,你可以在屬性的聲明前設(shè)置一個(gè)DefaultValueAttribute,在Attribute的構(gòu)造函數(shù)里傳入設(shè)置默認(rèn)值。
對(duì)于復(fù)雜的類型,比如Font,Color,你不能夠直接將這些類型的值傳遞給Attibute的構(gòu)造函數(shù)。相反你應(yīng)該提供Reset 和ShouldSerialize 方法,比如ResetBackgroundColor(),ShouldSerializeBackgroundColor()。
VS能夠根據(jù)方法的名稱來識(shí)別這種方法,比如Reset 方法把重置為設(shè)置默認(rèn)值,ShouldSerialize 方法檢查屬性是否是設(shè)置默認(rèn)值。過去我們把它稱之為魔術(shù)命名法,應(yīng)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e?.?A?l?i?g?n?m?e?n?t? = ?S?t?r?i?n?g?A?l?i?g?n?m?e?n?t?.?C?e?n?t?e?r?;?
b?r?e?a?k;?
}?
/?/ ?C?a?l?l? ?t?h?e? ?D?r?a?w?S?t?r?i?n?g? ?m?e?t?h?o?d? ?o?f? ?t?h?e? ?S?y?s?t?e?m?.?D?r?a?w?i?n?g? ?c?l?a?s?s? ?t?o? ?w?r?i?t?e? ? ?
/?/ ?t?e?x?t?.? ?T?e?x?t? ?a?n?d? ?C?l?i?e?n?t?R?e?c?t?a?n?g?l?e? ?a?r?e? ?p?r?o?p?e?r?t?i?e?s? ?i?n?h?e?r?i?t?e?d? ?f?r?o?m? ? ?
/?/ ?C?o?n?t?r?o?l?.? ? ? ? ? ? ? ? ? ? ? ? ?
e?.?G?r?a?p?h?i?c?s?.?D?r?a?w?S?t?r?i?n?g?(?
D?i?s?p?l?a?y?T?e?x?t?,?
F?o?n?t?,?
n?e?w ?S?o?l?i?d?B?r?u?s?h?(?T?e?x?t?C?o?l?o?r?)?,?
C?l?i?e?n?t?R?e?c?t?a?n?g?l?e?,? ?s?t?y?l?e?)?;?
}?
}?
}
在上面C# WinForm控件開發(fā)的代碼中,我增加了兩個(gè)屬性,一個(gè)是DisplayText,這是一個(gè)簡(jiǎn)單屬性,我們只需要在它的聲明前添加一個(gè)DefaultValue Attribute就可以了。
另外一個(gè)是TextColor屬性,這個(gè)復(fù)雜類型的屬性,所以我們提供了ResetTextColor和ShouldSerializeTextColor來實(shí)現(xiàn)默認(rèn)值。
C# WinForm控件開發(fā)設(shè)置默認(rèn)值的實(shí)現(xiàn)就講完了,但是有一點(diǎn)不要忽視了,你已經(jīng)設(shè)置默認(rèn)值,就應(yīng)該相應(yīng)的初始化這些屬性,比如我們例子中的代碼:
p?r?i?v?a?t?e ?S?t?r?i?n?g? ?_?d?i?s?p?l?a?y?T?e?x?t=”?H?e?l?l?o? ?W?o?r?l?d!”?;? ?
p?r?i?v?a?t?e ?C?o?l?o?r? ?_?t?e?x?t?C?o?l?o?r=C?o?l?o?r?.?R?e?d?;?
以上介紹的就是C# WinForm控件開發(fā)如何設(shè)置屬性的默認(rèn)值,希望對(duì)你有所幫助。
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@fc6vip.cn
文章轉(zhuǎn)載自:網(wǎng)絡(luò)轉(zhuǎn)載