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