How to put spaces on a bound enum title on picker - c#

I am attaching enum to a picker and onSelect i am binding to the actual value of the enum, not its title.
My enum is as follows:
public enum Reason
{
AnnualLeave = 12,
Emergency = 23,
MaternityLeave = 34
}
My class uses the following to bind the enum title to the picker
public Reason ReasonSelectedOption { get; set; }
public ObservableCollection<Reason> ReasonDisplay
{
get => new ObservableCollection<Reason>(Enum.GetValues(typeof(Reason)).OfType<Reason>().ToList());
}
The actual picker
<Picker
ItemsSource="{Binding ReasonDisplay}"
SelectedItem="{Binding ReasonSelectedOption}"
Title="Please Select"
HorizontalOptions="FillAndExpand" />
Everything works fine except in the actual picker, the options appear as AnnualLeave and MaternityLeave which is what's expected from my code but i want them to appear as Annual Leave and Maternity Leave (with the space inbetween) preserving the selecteditem value
Current case: When user selects AnnualLeave, selectedItem value is 12, if i convert to string the selected value becomes 0.
I am simply asking how to put spaces inbetween the enum options and also preserve the SelectedItem integer value

Here you have to keep in mind the internationalisation.
Even if you don't have localised texts now, you may have to support it in the future. So, keeping that in mind, you won't need simply to "split" the string, but to take a specific text from somewhere (i.e. translate it according to the culture).
You can achieve it with the help of some attributes, extension methods and some clever binding.
Let's say that you want to have a picker with 2 options - what is the property type. The PropertyType is an enum, that looks like this:
public enum PropertyType
{
House,
Apartment
}
Since the built-in Description attribute can't translate texts for us, we can use a custom attribute to assign a specific text to an enum type, like this:
public enum PropertyType
{
[LocalizedDescription(nameof(R.SingleFamilyHouse))]
House,
[LocalizedDescription(nameof(R.ApartmentBuilding))]
Apartment
}
The attribute code looks like this:
public class LocalizedDescriptionAttribute : DescriptionAttribute
{
private readonly ResourceManager resourceManager;
private readonly string resourceKey;
public LocalizedDescriptionAttribute(string resourceKey, Type resourceType = null)
{
this.resourceKey = resourceKey;
if (resourceType == null)
{
resourceType = typeof(R);
}
resourceManager = new ResourceManager(resourceType);
}
public override string Description
{
get
{
string description = resourceManager.GetString(resourceKey);
return string.IsNullOrWhiteSpace(description) ? $"[[{resourceKey}]]" : description;
}
}
}
R is my resx file. I have created a Resources folder and inside it I have 2 resx files - R.resx (for English strings) & R.de.resx (for German translation). If you don't want to have internationalisation now, you can change the implementation to get your strings from another place. But it is considered a good practice to always use a resx file, even if you only have 1 language. You never now what tomorrow may bring.
Here is my structure:
The idea behind LocalizedDescriptionAttribute class is that the built-in Description attribute isn't very useful for our case. So we'll have to take the resource key that we have provided it, translates and to override the Description attribute, which later we will reference.
Now we need to obtain the localised description text with this helper method:
public static class EnumExtensions
{
public static string GetLocalizedDescriptionFromEnumValue(this Enum value)
{
return !(value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(LocalizedDescriptionAttribute), false)
.SingleOrDefault() is LocalizedDescriptionAttribute attribute) ? value.ToString() : attribute.Description;
}
}
Now, when we create the bindings for the Picker, we won't just use a simple Enum, but a specific PropertyTypeViewModel, which will have 2 properties - the Enum itself and a Name that will be displayed.
public class PropertyTypeViewModel : BaseViewModel
{
private string name;
public string Name
{
get => name;
set => SetValue(ref name, value);
}
private PropertyType type;
public PropertyType Type
{
get => type;
set => SetValue(ref type, value);
}
public PropertyTypeViewModel()
{
}
public PropertyTypeViewModel(PropertyType type)
: this()
{
Type = type;
Name = type.GetLocalizedDescriptionFromEnumValue();
}
}
The important line is the last one - Name = type.GetLocalizedDescriptionFromEnumValue();
The final thing that is left is to set your Picker's ItemsSource to your collection of PropertyTypeViewModels and ItemDisplayBinding to be pointing to the Name property - ItemDisplayBinding="{Binding Name}"
That's it - now you have a Picker with dynamic localised strings.

You could use a converter
public class EnumToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return null;
var valueAsString = value.ToString();
valueAsString = valueAsString.SplitCamelCase();
return valueAsString;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
And for the SplitCamelCase I wrote this but I'm sure there are cleaner options:
public static string SplitCamelCase(this string str)
{
string result = "";
for (int i = 0; i < str.Count(); i++)
{
var letter = str[i];
var previousLetter = i != 0 ? str[i - 1] : 'A';
if (i != 0 && char.IsUpper(previousLetter) == false && char.IsUpper(letter)) result = result + " " + letter;
else result = result + letter;
}
return result;
}
Then just used it like so:
<TextBlock Text="{Binding Converter={StaticResource EnumToStringConverter}}"/>

Related

How to fetch an element's Display attribute in c# enums

I have below enum and I want to fetch its element's Display attribute based on values assigned to it.
I need to create a function where I need to pass a value(1 for Economic) and it will return me related element's Display attribute.
public enum ProbabilityNames
{
[Display(Name = "Economic Probability")]
Economic = 1,
[Display(Name = "Reliability Probability")]
Reliability = 2
}
You can use reflection for that:
public static class ProbabilityNamesExtensions
{
public static DisplayAttribute GetDisplay(this ProbabilityNames value) =>
typeof(ProbabilityNames)
.GetField(Enum.GetName(typeof(ProbabilityNames), value))
.GetCustomAttributes(false)
.SingleOrDefault(attr => attr is DisplayAttribute) as DisplayAttribute;
public static string GetDisplayName(this ProbabilityNames value) =>
value.GetDisplay()?.Name;
}
You can use it like this:
ProbabilityNames.Economic.GetDisplay();
Or if you need to get the display based on an int value, you can just cast it:
((ProbabilityNames)1).GetDisplay();

How to create browseable class-properties in .NET / Visual studio

How I can make something like this in VS properties Window (collapsible multi properties):
I tried such code:
Test z = new Test();
[ Browsable(true)]
public Test _TEST_ {
get { return z; }
set { z = value; }
}
Where "Test" class is:
[Browsable(true)]
public class Test {
[Browsable(true)]
public string A { get;set; }
[Browsable(true)]
public string B { get;set; }
}
But this gives me only grayed-out name of class
Alright, I got something to work that may satisfy your case.
To get a class to expand in the PropertyGrid, you have to add a TypeConverterAttribute to it, referencing the type of an ExpandableObjectConverter (or something else that derives from it).
[TypeConverter(typeof(ExpandableObjectConverter))]
public class Test
{
[Browsable(true)]
public string A { get; set; }
[Browsable(true)]
public string B { get; set; }
}
The only problem is that it now displays the type name (the return value of its ToString() method as the value of your class). You can either live with it (which you probably won't want to), change the ToString() return value to something more fitting or use a custom TypeConverter for that case.
I'll show you a quick implementation on how the latter could be done:
internal class TestConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
return "";
return base.ConvertTo(context, culture, value, destinationType);
}
}
And then you would write this, instead of what I wrote above:
[TypeConverter(typeof(TestConverter))]
public class Test
{
[Browsable(true)]
public string A { get; set; }
[Browsable(true)]
public string B { get; set; }
}
This just empties the information and prevents the user to enter some other value. You probably want to show something more descriptive which is completely up to you.
It is also possible to get information and parse it into useful values. A good example would be the location, which is an object of type Point visualized with [10,5] when X is 10 and Y is 5. When you enter new values they are parsed and set to the integers that are referenced by the original string.
Because I couldn't find much about the topic, I looked up some references in ReferenceSource, because it had to be done before. In my case, I peeked into ButtonBase and FlatButtonAppearance of WindowsForms to see how Microsoft did it, back in the day.
Hope I could help.
Here is the TypeConverter Class. This allows VS properties to access your object as strings, and convert back to it from strings.
for more about TypeConversion.
class MultiPropConverter : ExpandableObjectConverter
{
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)
{
string[] v = ((string)value).Split(new char[] { ',' });
if(v.Length == 3) // Check that there are no ',' in your string(s) A.
{
return new DropDownProperties(v[0], float.Parse(v[1]), int.Parse(v[2]));
}
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture,
object value, Type destinationType)
{
if (destinationType == typeof(string)) // What VS properties ask for to display
{
DropDownProperties dDP = (DropDownProperties)value;
return dDP.A + "," + dDP.B.ToString() + "," + dDP.C.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
the Multi-Property Class:
[TypeConverter(typeof(MultiPropConverter))]
public class DropDownProperties
{
[Description("Description of A")]
public string A { get; set; } = "Default";
[Description("Description of B")]
public float B { get; set; } = 0f;
[Description("Description of C")]
public int C { get; set; } = 1;
}
And then class instantiation:
[Description("Category Description"), Category("ACategory")]
public DropDownProperties dropProp { get; set; } = new DropDownProperties()
{ A = "Hello World", B = "0.1", C = 0};
You do not need the Browsable attribute if you include a category or description for the item.
Cheers!
In addition to the already good answers by others.
Browseable(true/false) means it can be browsed in the property window.
Please note, the Visual Studio properties editor will only show public properties. Private properties are hidden and can't be browsed for various reasons.
Public properties are browsable by default.
https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.browsableattribute?view=netcore-3.1
The designer will always only show one value per default for strings, multi-property dropdowns only work for integers afaik.
Also, there is EditorBrowsable which defines whether or not Intellisense shows your property.
You can do something like this:
public class Column
{
[EditorBrowsable(EditorBrowsableState.Always)]
public string name { get; set; }
[EditorBrowsable(EditorBrowsableState.Never)]
}
https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.editorbrowsablestate?view=netcore-3.1
https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.editorbrowsableattribute?view=netcore-3.1

My custom value converter causes XAML validation tool to fail

I've created a custom converter that performs converting of values based on configured mapping. It looks like below
public class UniversalConverter : List<ConverterItem>, IValueConverter
{
private bool useDefaultValue;
private object defaultValue;
public object DefaultValue
{
get { return defaultValue; }
set
{
defaultValue = value;
useDefaultValue = true;
}
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
foreach (var item in this)
if (Equals(item.From, value))
return item.To;
if (useDefaultValue)
return DefaultValue;
throw new ConversionException(string.Format("Value {0} can't be converted and default value is not allowed", value));
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
foreach (var item in this)
if (Equals(item.To, value))
return item.From;
throw new ConversionException(string.Format("Value {0} can't be converted back", value));
}
}
public class ConverterItem
{
public object From { get; set; }
public object To { get; set; }
}
public class ConversionException : Exception
{
public ConversionException() { }
public ConversionException(string message) : base(message) { }
}
Sample XAML is below
<core:UniversalConverter x:Key="ItemCountToVisiblityConverter" DefaultValue="{x:Static Visibility.Collapsed}">
<core:ConverterItem To="{x:Static Visibility.Visible}">
<core:ConverterItem.From>
<system:Int32>0</system:Int32>
</core:ConverterItem.From>
</core:ConverterItem>
</core:UniversalConverter>
Now everything builds and works fine, but if I use it XAML Visual Studio underscores the whole file with curvy blue lines and shows two kind of mistakes:
1) If converter is put into ResourceDictionary AND is assigned an x:Key attribute it shows Missing key value on 'UniversalConverter' object
2) If I assign DefaultValue property any value (e.g {x:Null}) the message is XAML Node Stream: Missing EndMember for 'StuffLib.UniversalConverter.{http://schemas.microsoft.com/winfx/2006/xaml}_Items' before StartMember 'StuffLib.UniversalConverter.DefaultValue'
What is the reason for those messages? I can live with them but they hide all other compiler and ReSharper markings
Don't inherit from list, just create Items property in your converter:
[ContentProperty("Items")]
public class UniversalConverter : IValueConverter
{
public ConverterItem[] Items { get; set; }
public object DefaultValue { get; set; }
//all other stuff goes here
}
and xaml:
<l:UniversalConverter x:Key="MyConverter">
<x:Array Type="l:ConverterItem">
<l:ConverterItem From="..." To="..." />
Based on answer given by #Leiro
[ContentProperty("Items")]
public class UniversalConverter : IValueConverter
{
public UniversalConverter()
{
Items = new List<ConverterItem>();
}
public List<ConverterItem> Items { get; private set; }
//All other logic is the same
}
Note that this way you won't need to wrap items in collection in XAML
Resulting XAML
<core:UniversalConverter x:Key="ItemCountToVisiblityConverter" DefaultValue="{x:Static Visibility.Collapsed}">
<core:ConverterItem To="{x:Static Visibility.Visible}">
<core:ConverterItem.From>
<system:Int32>0</system:Int32>
</core:ConverterItem.From>
</core:ConverterItem>
</core:UniversalConverter>
It's because it is being used at design time but there is no data so I suspect a NullReferenceException is being thrown. Try checking for design time mode as follows at the top of the IValueConverter.Convert() method body:
// Check for design mode.
if ((bool)(DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue))
{
return false;
}

Parse StringValueAttribute to return Enum

I currently have a windows phone 8.1 runtime project with enums that use a string value attribute. I want to be able to get an enum value by using the string value attribute, for example use "world" to get the enum value of summer. I am using Windows phone 8.1 runtime so most methods that I have found do not work.
Thanks in advance.
public enum test
{
[StringValue("hello")]
school,
[StringValue("world")]
summer,
[StringValue("fall")]
car
}
public class StringValueAttribute : Attribute
{
private string _value;
public StringValueAttribute(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
To get to your Attributes you will need to use a method/extension. Folowing this question and answer you can make such a thing:
public class StringValueAttribute : Attribute
{
private string _value;
public StringValueAttribute(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
public static string GetStringValue(Enum value)
{
Type type = value.GetType();
FieldInfo fi = type.GetRuntimeField(value.ToString());
return (fi.GetCustomAttributes(typeof(StringValueAttribute), false).FirstOrDefault() as StringValueAttribute).Value;
}
}
Then using this line of code:
string stringTest = StringValueAttribute.GetStringValue(test.summer);
will give a result of "world". (Opposite what you wanted, but hopefuly will give you an idea how to deal with the problem).
Depending on what you want to achieve, you can probably use different methods linke: using Dictionary, struct, properties and probably different ways.
As for parsing Enum values you can achieve it like this:
test testValue = test.summer;
string testString = testValue.ToString();
test EnumValue = (test)Enum.Parse(typeof(test), testString);
EDIT
If you want to get enum from attribute, then this method (probably should be improved) should do the job:
public static T GetFromAttribute<T>(string attributeName)
{
Type type = typeof(T);
return (T)Enum.Parse(typeof(T), type.GetRuntimeFields().FirstOrDefault(
x => (x.CustomAttributes.Count() > 0 && (x.CustomAttributes.FirstOrDefault().ConstructorArguments.FirstOrDefault().Value as string).Equals(attributeName))).Name);
}
Usage:
test EnumTest = StringValueAttribute.GetFromAttribute<test>("world");

Converting a string to a custom enum

I'm trying to set a custom enum property on a custom object by looking at a string value that is held in another object, but I keep getting the error "cannot reference a type through an expression."
so far I've tried
rec.Course = (CourseEnum)Enum.Parse(typeof(CourseEnum), rr.course);
where rec.Course wants a member of the CourseEnum Enumeration, and rr.course is a string.
I also tried to do a switch statement where the value of rr.course is checked (there are only certain values it can be) but get the same result
the enum is defined as follows:
public enum CourseEnum
{
[StringValue("Starters")]
Starters,
[StringValue("Main Course")]
MainCourse,
[StringValue("Desserts")]
Desserts
};
public class StringValue : System.Attribute
{
private string _value;
public StringValue(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
public static class StringEnum
{
public static string GetStringValue(Enum value)
{
string output = null;
Type type = value.GetType();
//Check first in our cached results...
//Look for our 'StringValueAttribute'
//in the field's custom attributes
FieldInfo fi = type.GetRuntimeField(value.ToString());
StringValue[] attrs =
fi.GetCustomAttributes(typeof(StringValue),
false) as StringValue[];
if (attrs.Length > 0)
{
output = attrs[0].Value;
}
return output;
}
}
I can see in your code that your using Enum.Parse with CourseEnum and it should be recipeCourse I presume.
I can't spot any place in your sample code where4 CourseEnum is defined.
A #Hans Kesting said, the answer was here: Why can not reference a type through an expression?
The problem was using a field that has an enum type with the enum type itself.

Categories