[英]C# stop property change at runtime
我一直在嘗試使用設計器中設置的一些自定義屬性來構建用戶控件。 但是,控件涉及一些不應在運行時調整的互操作代碼和設置。 有沒有辦法在設計師代碼最初設置后停止更改的值?
你能修改屬性定義嗎? 一種方法是,向屬性setter添加一個sentinel,並且只允許一個set操作(通常由InitializeComponent()完成):
private int _myProperty;
private bool _isMyPropertySet = false;
public int MyProperty
{
set
{
if (!_isMyPropertySet)
{
_isMyPropertySet = true;
_myProperty = value;
}
else
{
throw new NotSupportedException();
}
}
}
邁克爾提供了一個很好的答案,它將在運行時解決您的問題。 但是,在設計時,如果您需要能夠多次更改該值(這是設計時間,概率可能很高),那么您需要將DesignMode檢查與Michaels示例結合使用:
private int _myProperty;
private bool _isMyPropertySet = false;
public int MyProperty
{
set
{
if (this.DesignMode || !_isMyPropertySet)
{
_isMyPropertySet = true;
_myProperty = value;
}
else
{
throw new NotSupportedException();
}
}
}
現在,您可以在設計過程中將此值編輯到您的內容中,而不會遇到NotSupportedException()並在第二組上獲得一個拙劣的設計器。
你可以在屬性setter中拋出一個異常?
public int SomeProperty {
set {
if(designerComplete) {
throw new IllegalOperationException();
}
}
}
將designerComplete設置為類變量 - 在構造函數中調用InitializeComponent方法后將其設置為true。
WinForms體系結構提供了一種內置方法來測試代碼當前是否在設計模式下執行 - Component.DesignMode屬性。
所以你可能想要一個像這樣的實現:
private int _foo;
public int Foo
{
get { return _foo; }
set
{
if (this.DesignMode)
throw new InvalidOperationException();
_foo = value;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.