我做了一个 UserControl 的例子,但仍然(花了一整天)无法解决我的问题。
我希望 UserControl 有一个复杂的属性,在设计时查看属性网格内的属性,能够更改它等等。复杂属性很简单——它是一个具有一个字符串属性的类。
现在我有两个问题:
1) 当我在属性网格中更改文本的值时 - 值不会转到 Form1.Designer.cs
2)有时当我重建项目(甚至不需要运行)时,我有一个 VS 的弹出窗口,其中说 SettingsCoverter 无法将设置转换为 InstanceDescriptor。这些设置类是我的。请帮助解决这个问题。
[TypeConverter(typeof(SettingsConverter))]
public class Settings : INotifyPropertyChanged
{
private string stringText = "123";
public string StringText
{
get { return stringText; }
set
{
stringText = value;
OnPropertyChanged("StringText");
}
}
public Settings()
{
}
public Settings(string fText)
{
StringText = fText;
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
和
class SettingsConverter : ExpandableObjectConverter
{
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
{
return true;
}
public override object CreateInstance(ITypeDescriptorContext context, System.Collections.IDictionary propertyValues)
{
return new Settings((string)propertyValues["StringText"]);
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string) || destinationType == typeof(InstanceDescriptor))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (value is Settings)
{
if (destinationType == typeof(InstanceDescriptor))
{
Settings settings = (Settings)value;
object[] properties = new object[1];
Type[] types = new Type[1];
types[0] = typeof(string);
properties[0] = settings.StringText;
ConstructorInfo ci = typeof(Settings).GetConstructor(types);
return new InstanceDescriptor(ci, properties);
}
if (destinationType == typeof(string))
{
Settings settings = (Settings)value;
return settings.StringText;
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value == null)
return "";
if (value is string)
return new Settings(value as string);
return base.ConvertFrom(context, culture, value);
}
}