在我的示例中,我使用了一個PropertyGrid控件並獲取了我的所有屬性和值。避免來自PropertyGrid的異常
當我一個屬性更改爲無效值,如「123456789008765」的整型字段,它引發以下錯誤:
我需要避免這個錯誤,如果給定值無效我需要分配一個默認值(在這種情況下爲13, 13
)。我怎樣才能做到這一點?
在我的示例中,我使用了一個PropertyGrid控件並獲取了我的所有屬性和值。避免來自PropertyGrid的異常
當我一個屬性更改爲無效值,如「123456789008765」的整型字段,它引發以下錯誤:
我需要避免這個錯誤,如果給定值無效我需要分配一個默認值(在這種情況下爲13, 13
)。我怎樣才能做到這一點?
簡答
的PropertyGrid
使用TypeConverter
到string
轉換成你的財產的價值和你的財產值轉換爲string
。
該錯誤消息是由Size
類型轉換器中的字符串轉換爲尺寸值時升高。
從字符串轉換時,您需要更改屬性的行爲。 您應該創建一個自定義類型轉換器並將其註冊爲屬性,以便在從字符串轉換爲屬性值時處理異常。
路徑解決方案
這裏是你要解決的主要問題:
你應該知道什麼
的PropertyGrid
使用TypeConverter
到string
轉換成你的財產的價值和你的財產值轉換爲string
。
爲一個字符串轉換成你的財產,你應該Implement a Type Converter當自定義屬性網格的行爲。
CanConvertFrom
和ConvertFrom
。當你說這個類型可以從string
轉換,那麼你將允許用戶輸入屬性網格。ConvertTo
。這樣你提供你的屬性值的字符串表示。ExpandableObjectConverter
派生自定義轉換器。TypeConverter
屬性。Size
默認類型轉換器可以使用TypeDescriptor.GetConverter(typeof(Size));
解決方案
錯誤消息是由Size
類型轉換器提高。所以我們需要在從字符串轉換時改變屬性的行爲。
根據上述信息,我們爲您的財產實施自定義類型轉換器。在實現中,我們從ExpandableObjectConverter
繼承,然後在構造函數中,我們得到Size
的默認轉換器,並在覆蓋所提到的方法時使用它。
的主要要求是在ConvertFrom
實現,在那裏,我們嘗試將字符串轉換爲Size
和發生異常時,而不是我們使用DefaultValue
您設置使用屬性的,如果沒有默認值,我們使用0,0
作爲價值。
實施
創建一個轉換器:
public class CustomSizeConverter : ExpandableObjectConverter
{
TypeConverter converter;
public CustomSizeConverter()
{
converter = TypeDescriptor.GetConverter(typeof(Size));
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return converter.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
try
{
return converter.ConvertFrom(context, culture, value);
}
catch (Exception)
{
var d= context.PropertyDescriptor.Attributes.OfType<DefaultValueAttribute>().FirstOrDefault();
if (d != null)
return d.Value;
else
return new Size(0,0);
}
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
return converter.ConvertTo(context, culture, value, destinationType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return converter.CanConvertTo(context, destinationType);
}
}
這裏是你的類,它包含一個Size
屬性與新轉換器:
public class MyObject
{
public MyObject() { SomeSize = new Size(13, 13); }
public string SomeText { get; set; }
[TypeConverter(typeof(CustomSizeConverter))]
[DefaultValue(typeof(Size), "13,13")]
public Size SomeSize { get; set; }
}
不要忘記,包括需要使用:
using System;
using System.Linq;
using System.Drawing;
using System.ComponentModel;
http://stackoverflow.com/questions/23219139/propertygrid-validation,http://stackoverflow.com/questions/19398840/validation-within-the-winforms-propertygrid, – CodeCaster
它不工作,當我輸入無效數據會自動拋出該錯誤,而不會觸及事件(propertyGrid_PropertyValueChanged) –
您是否應該打開屬性,使其顯示在兩行上,然後分別編輯每個部分?點擊「項目大小」左側的小三角。 – RenniePet