Reputation: 89
A project I am working on has an enum defined that has only two states. I am using a toggle button to switch the property value.
Using the value converter that I wrote for binding enums to a set of radio buttons does not work since it only changes the value one way due to the Binding.DoNothing
.
Here is the enum to boolean converter used for the radio buttons that only changes the value in one direction:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.Equals(true) ? parameter : Binding.DoNothing;
}
As a workaround I modified this specifically for the enum that I am using as shown below by replacing Binding.DoNothing
with MyEnum.Off
in the ConvertBack
method
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.Equals(true) ? parameter : MyEnum.Off;
}
Is there a better way to switch this enum value returned to enable the toggle button to switch the enum to the off state that would be reusable across different Enum types?
Upvotes: 3
Views: 2241
Reputation: 182
If you're enum has only 2 states, wouldn't it be simpler to just use a bool? Then you could externalize that to a function that switches the bool to true/false based on its current value
Edit:
After reading the comment left by @Kevin, I realized I misunderstood the original question. The below should hopefully be more in line with what you are asking for. It will take an enum T and iterate through it, returning the int
index of each next item in the sequence until it reaches the end, where it will return the first item again(0).
private int SwitchEnum<T>(Enum G)
{
int next = Convert.ToInt32(G) + 1;
if (Enum.IsDefined(typeof(T), next))
{
return next;
}
else
{
return 0;
}
}
You can call this function as follows:
MyEnum a = new MyEnum(); //Assuming MyEnum is your enum
a = (MyEnum)SwitchEnum<MyEnum>(a);
Upvotes: 0
Reputation: 5944
The simplest without any type/null/etc checking is the following:
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return System.Convert.ToBoolean(value);
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return Enum.ToObject(targetType, value);
}
System.Convert.ToBoolean
accepts any value type without throwing an exception.
You could als do some additional type checking such as if (targetType.IsEnum)
, but that's up to you.
According to msdn: Enum.ToObject()
only accepts SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64.
, but I suspect it uses System.Convert
internally so a boolean is also accepted.
Upvotes: 2