I can't convert showing property from uint to string format in PropertyGrid control. This is what I do:
var fruits = new SortedDictionary<uint, string>
{
{0, "Apple"},
{1, "Orange"},
{3, "Watermelon"},
};
public class FruitConverter : StringConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof(uint) && fruits.ContainsKey(sourceType))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture,
object value)
{
if (sourceType == typeof(uint) && fruits.ContainsKey(sourceType))
return fruits[value];
return base.ConvertFrom(context, culture, value);
}
}
public class Fruit
{
[ReadOnly(true)]
[DisplayName("Type of fruit")]
[TypeConverter(typeof(FruitConverter))]
public uint FruitTypeCode { get; set; }
}
But property FruitTypeCode is still is shown as uint and not as a string, what I did wrong ?
This should work:
public class FruitConverter : TypeConverter
{
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
return fruits[(uint)value];
}
}
Related
I have an enum that contains duplicate values. For example:
public enum DataVals : byte
{
C1_Route1to2 = 1,
C4_Route3to5 = 1,
C6_Route1to2 = 2,
C7_Route3to5 = 2
}
The values C# are just internal values within my application. Depending on which route is selected by the user, route is another property in the class, a 1 could mean use C1 or C4. The problem is I am using a PropertyGrid in my Winform and this property displays the duplicate values as having the same name. So C1_Route1to2 shows up twice instead of both C1_Route1to2 and C4_Route3to5.
How do I tell the PropertyGrid to display each unique name, rather than duplicating the values?
Although I agree with Gabriel, you could achieve what you need using the TypeConverter as I mentioned before. You might need to change the editor to allow selecting more than one enum if it has the FlagsAttribute...
Place the attribute:
[TypeConverter(typeof(ComplexEnumConverter ))]
public enum DataVals : byte
{
C1_Route1to2 = 1,
C4_Route3to5 = 1,
C6_Route1to2 = 2,
C7_Route3to5 = 2
}
And here is the converter:
public class ComplexEnumConverter : EnumConverter
{
public bool IsFlagged { get; }
public string[] EnumValues { get; }
public ComplexEnumConverter(Type type)
: base(type)
{
IsFlagged = TypeDescriptor.GetAttributes(type).OfType<FlagsAttribute>().Any();
EnumValues = Enum.GetNames(type);
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var str = value as string;
if (!string.IsNullOrWhiteSpace(str))
{
var values = str.Split(',').Select(s => s.Trim());
var enumValue = Enum.Parse(EnumType, values.First());
if (IsFlagged)
{
var temp = (int)enumValue;
foreach (var item in values.Skip(1))
{
temp |= (int)Enum.Parse(EnumType, item);
}
enumValue = temp;
}
return enumValue;
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
var type = value?.GetType();
if (type == EnumType)
{
var list = new List<string>();
int k = (int)value;
foreach (var item in Enum.GetNames(type))
{
var current = (int)Enum.Parse(type, item);
if ((k & current) == current)
{
list.Add(item);
}
}
return list.Aggregate((c, n) => $"{c}, {n}");
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return context.PropertyDescriptor.PropertyType.IsEnum;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return context.PropertyDescriptor.PropertyType.IsEnum;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return new StandardValuesCollection(EnumValues);
}
}
How can I achieve the following JSON representation of Id class when used in another class?
class Car
{
public StringId Id { get; set; }
public string Name { get; set; }
}
class StringId
{
public string Value { get; set; }
}
// ---------------------------------------------
// Desired representation
{ "Id": "someId", "Name": "Ford" }
// Default (undesired) representation
{ "Id" : { "Value": "someId" }, "Name": "Ford" }
You could add a TypeConverter for StringId. Json.NET will pick up the type converter and use it to convert it from and to a string:
[TypeConverter(typeof(StringIdConverter))]
class StringId
{
public string Value { get; set; }
}
class StringIdConverter : TypeConverter
{
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(StringId))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
return new StringId { Value = (string)value };
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value is StringId)
{
return ((StringId)value).Value;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
If your string representation contains embedded numeric or date/time data, be sure to convert that data using the culture passed in rather than the default, current culture. Json.NET will call the converter with the correct culture, which is the invariant culture by default, thus ensuring the generated JSON files are portable between cultures.
Sample fiddle.
Note however that, if you are using .Net Core, support for type converters was only added as of Json.NET 10.0.1. And support for type converters in Json.NET Portable builds is not available as of 10.0.3.
Alternatively, if you don't mind adding Json.NET-specific attributes to your type, you could use a custom JsonConverter:
[JsonConverter(typeof(StringIdConverter))]
class StringId
{
public string Value { get; set; }
}
class StringIdConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(StringId);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var token = JToken.Load(reader);
return new StringId { Value = (string)token };
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var id = (StringId)value;
writer.WriteValue(id.Value);
}
}
You can also set the converter in global settings.
Sample fiddle.
You can override the ToString method of the StringId class to return the value
public override string ToString()
{
return this.Value;
}
You will need a TypeConverter later to deserialize from string to StringId
public class StringIdConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
return new StringId(value.ToString());
}
return base.ConvertFrom(context, culture, value);
}
}
And decorate your StringId class with this attribute
[TypeConverter(typeof(StringIdConverter))]
public class StringId{
...
}
But it does. I have created a type converter that implements CanConvertFrom(), defined the type converter on type type. Everything runs fine. This is just XAML that defines design time data for Blend, but the error is very annoying.
It appears that VS is just not trying to use the type converter. Is there some place that you have to register type converters so that they will be used at design time by Visual Studio?
[TypeConverter(typeof(MyTypeTypeConverter))]
[DataContract]
public struct MyType
{
[DataMember]
internal readonly float _Value;
public MyType(float value)
{
_Value = (float)Math.Round(value, 3);
}
}
public class MyTypeTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(String))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
float f;
if (!Single.TryParse((string)value, out f))
return null;
return new MyType(f);
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
return ((MyType)value).ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
I have following enumeration.
public enum Digits
{One, Two, Three}
and a property with two entries.
public List<Digits> DigitList{get;set;}
DigitList.Add(Digits.One); DigitList.Add(Digits.Three);
When this object is bound to PropertyGrid it is displayed as (Collection) and when it is opened (using small browse button) an exception with (no useful message) is displayed. I am confused how the PropertyGrid interprets list of enumerations.
I searched for a solution, but all i could find was about how to bind a enum value, not list of enums.
You have to create a TypeConverter Class that will help the PropertyEditor to parse the Enum into a PropertyEditor.
Sample TypeConverter
public class FooDataTypeConverter : TypeConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
return base.GetStandardValues(context);
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return (sourceType.Equals(typeof(Enum)));
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return (destinationType.Equals(typeof(String)));
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
return (ValidationDataType)Enum.Parse(typeof(ValidationDataType), value.ToString(), true);
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (!destinationType.Equals(typeof(string)))
throw new ArgumentException("Can only convert to string", "destinationType");
if (!value.GetType().BaseType.Equals(typeof(Enum)))
throw new ArgumentException("Can only convert an instance of enum", "value");
string name = value.ToString();
object[] attr =
value.GetType().GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attr.Length > 0) ? ((DescriptionAttribute)attr[0]).Description : name;
}
}
After add this declaration to the enums that you want to parse in a propertyeditor.
[TypeConverter(typeof(FooDataTypeConverter ))]
public enum ValidationDataType
{
/// <summary>
/// None
/// </summary>
[Description("None")]
None,
.....
}
The last step is to add it to the property of your component that will show in the propertyeditor
[Category("Behavior")]
[Description("Gets or sets the type of data that will be compared")]
[TypeConverter(typeof(DataTypeConverter))]
[EditorAttribute(typeof(ValidatorTypeEditor), typeof(System.Drawing.Design.UITypeEditor))]
public ValidationDataType Type
{
get { return this.type; }
set
{
this.type = value;
if (this is RangeValidator)
{
this.SetRange();
}
}
}
So I've got a ConfigurationSection/ConfigurationElementCollection that has a configuration like this:
<mimeFormats>
<add mimeFormat="text/html" />
</mimeFormats>
And here is how I handle the mimeFormats:
public class MimeFormatElement: ConfigurationElement
{
#region Constructors
/// <summary>
/// Predefines the valid properties and prepares
/// the property collection.
/// </summary>
static MimeFormatElement()
{
// Predefine properties here
_mimeFormat = new ConfigurationProperty(
"mimeFormat",
typeof(MimeFormat),
"*/*",
ConfigurationPropertyOptions.IsRequired
);
}
private static ConfigurationProperty _mimeFormat;
private static ConfigurationPropertyCollection _properties;
[ConfigurationProperty("mimeFormat", IsRequired = true)]
public MimeFormat MimeFormat
{
get { return (MimeFormat)base[_mimeFormat]; }
}
}
public class MimeFormat
{
public string Format
{
get
{
return Type + "/" + SubType;
}
}
public string Type;
public string SubType;
public MimeFormat(string mimeFormatStr)
{
var parts = mimeFormatStr.Split('/');
if (parts.Length != 2)
{
throw new Exception("Invalid MimeFormat");
}
Type = parts[0];
SubType = parts[1];
}
}
And obviously I need a TypeConverter that actually does something (instead of this empty shell):
public class MimeFormatConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
throw new NotImplementedException();
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
throw new NotImplementedException();
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
throw new NotImplementedException();
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
throw new NotImplementedException();
}
}
How do I set up a TypeConverter that will allow type conversion from/to string? I've tried using the MSDN examples but I keep getting error message:
TypeConverter cannot convert from System.String.
Essentially, how can it be set up so that it will just work with whatever ConfigurationSection is trying to do?
You can put TypeConverterAttribute on the property to tell the serializer how to handle it.
[TypeConverter(typeof(MimeFormatConverter))]
[ConfigurationProperty("mimeFormat", IsRequired = true)]
public MimeFormat MimeFormat
{
get { return (MimeFormat)base[_mimeFormat]; }
}
Try this:
TestSection.cs
public class TestSection : ConfigurationSection
{
private static readonly ConfigurationProperty sFooProperty = new ConfigurationProperty("Foo",
typeof(Foo),
null,
new FooTypeConverter(),
null,
ConfigurationPropertyOptions.None);
public static readonly ConfigurationPropertyCollection sProperties = new ConfigurationPropertyCollection();
static TestSection()
{
sProperties.Add(sFooProperty);
}
public Foo Foo
{
get { return (Foo)this[sFooProperty]; }
set { this[sFooProperty] = value; }
}
protected override ConfigurationPropertyCollection Properties
{
get { return sProperties; }
}
}
Foo.cs
public class Foo
{
public string First { get; set; }
public string Second { get; set; }
public override string ToString()
{
return First + ',' + Second;
}
}
FooTypeConverter.cs
public class FooTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return (sourceType == typeof(string));
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string val = value as string;
if (val != null)
{
string[] parts = val.Split(',');
if (parts.Length != 2)
{
// Throw an exception
}
return new Foo { First = parts[0], Second = parts[1] };
}
return null;
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return (destinationType == typeof(string));
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
Foo val = value as Foo;
if (val != null)
return val.ToString();
return null;
}
}
I figured it out. Here is the solution:
public class MimeFormatElement: ConfigurationElement
{
#region Constructors
/// <summary>
/// Predefines the valid properties and prepares
/// the property collection.
/// </summary>
static MimeFormatElement()
{
// Predefine properties here
_mimeFormat = new ConfigurationProperty(
"mimeFormat",
typeof(MimeFormat),
"*/*",
ConfigurationPropertyOptions.IsRequired
);
_properties = new ConfigurationPropertyCollection {
_mimeFormat, _enabled
};
}
private static ConfigurationProperty _mimeFormat;
private static ConfigurationPropertyCollection _properties;
[ConfigurationProperty("mimeFormat", IsRequired = true)]
public MimeFormat MimeFormat
{
get { return (MimeFormat)base[_mimeFormat]; }
}
}
/*******************************************/
[TypeConverter(typeof(MimeFormatConverter))]
/*******************************************/
public class MimeFormat
{
public string Format
{
get
{
return Type + "/" + SubType;
}
}
public string Type;
public string SubType;
public MimeFormat(string mimeFormatStr)
{
var parts = mimeFormatStr.Split('/');
if (parts.Length != 2)
{
throw new Exception("Invalid MimeFormat");
}
Type = parts[0];
SubType = parts[1];
}
}
public class MimeFormatConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return new MimeFormat((string)value);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
var val = (MimeFormat)value;
return val.Type + "/" + val.SubType;
}
}
From this point, you have to create the convert sections within the ConvertTo and ConvertFrom methods
public override object ConvertFrom( ITypeDescriptorContext context, CultureInfo culture, object value ) {
if ( value == null )
return null;
try {
if ( value is string ) {
string s = (string)value;
// here is where you look at the string to figure out the MimeFormat
// like so....
return new MimeFormat( s );
}
throw new NotSupportedException( NotSupportedException( value.GetType(), typeof(MimeFormat) );
}
public override object ConvertTo( ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType ) {
if ( value == null )
return null;
MimeFormat p = (MimeFormat)value;
if ( destinationType == typeof( String ) )
return p.ToString();
throw new NotSupportedException( NotSupportedException( typeof(MimeFormat), destinationType ) );
}
EDITED
You also need to override the CanConvert functions as well.
public override bool CanConvertFrom( ITypeDescriptorContext context, Type sourceType ) {
if ( sourceType == typeof( string ) )
return true;
return false;
}
public override bool CanConvertTo( ITypeDescriptorContext context, Type destinationType ) {
if ( destinationType == typeof( string ) )
return true;
return false;
}