避免使用PropertyGrid中的例外

时间:2015-11-24 10:16:14

标签: c# .net winforms windows-forms-designer propertygrid

在我的示例中,我使用了一个PropertyGrid控件并获取了我的所有属性和值。

当我将一个属性更改为无效值时,例如" 123456789008765"对于整数字段,它会引发以下错误:

enter image description here

我需要避免这个错误,如果给定的值无效,我需要指定一个默认值(在本例中为13, 13)。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

简答

PropertyGrid使用TypeConverterstring转换为您的媒体资源价值,并将您的媒体资源价值转换为string

将字符串转换为大小值时,Size的类型转换器会引发错误消息。

从字符串转换时,您需要更改属性的行为。 您应该创建一个自定义类型转换器并为您的属性注册它,以便在从字符串转换为您的属性值时处理异常。

解决方案的途径

以下是您应该解决的主要问题:

  • 让用户输入属性网格。
  • 在属性网格中显示属性的字符串表示形式。
  • 让用户扩展属性。
  • 当字符串无法转换为您的属性值时,请使用默认值,而不是显示消息框。

你应该知道什么

PropertyGrid使用TypeConverterstring转换为您的媒体资源价值,并将您的媒体资源价值转换为string

要在将字符串转换为属性时自定义属性网格的行为,您应该Implement a Type Converter

  • 要将字符串转换为您的媒体资源类型,您应该覆盖CanConvertFromConvertFrom。当您说类型可以从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;