在我的示例中,我使用了一个PropertyGrid控件并获取了我的所有属性和值。
当我将一个属性更改为无效值时,例如" 123456789008765"对于整数字段,它会引发以下错误:
我需要避免这个错误,如果给定的值无效,我需要指定一个默认值(在本例中为13, 13
)。我怎么能这样做?
答案 0 :(得分:3)
简答
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;