Thursday, 19 July 2012

Lightswitch: Get choice value of a property

I have found quite a number of things from the internet when I was doing my Lightswitch development, but I cannot remember most of the source now. So thanks for people in the community who have contributed but sorry I cannot acknowledge them properly.

 

Here is an extension method for getting the choice value of a property in code:

public static string GetDisplayedChoiceValue(this IEntityStorageProperty property)
{
// If the value is null, it has no display value
if (null == property.Value)
return null;

string valueAsString = property.Value.ToString();
// Get the list of choices for this property
IEnumerable<ISupportedValueAttribute> choices = property.
GetModel().Attributes.OfType<ISupportedValueAttribute>();
// Find the choice that matches the property value
ISupportedValueAttribute choice = choices.Single(
c => String.Equals(c.Value, valueAsString, StringComparison.Ordinal));

// If the choice does not have a display name, return the choice value instead
if (String.IsNullOrEmpty(choice.DisplayName))
return choice.Value;
else
return choice.DisplayName;
}

To use it with your object:

CodeName = o.Details.Properties.Code.GetDisplayedChoiceValue(),

No comments:

Post a Comment