Wednesday, May 5, 2010

WPF Filter Combo Box

I was asked to write a prototype for a project that I am currently working on.
They wanted to be able to selected for a master combo box and filter the selection of the sub-child combo boxes.

I read an article on stackoverflow, which I base my code sample on.

To do this Master-Child Hierarchy, I have implemented it through the use of the attribute property, by creating a custom attribute (PriorityLevel).

public class Football
{
[PriorityLevel(1)]
public League League { get; set; }

[PriorityLevel(2)]
public string Team { get; set; }
}

I have created the custom attribute with the use of an interface (IAttribute).

public class PriorityLevelAttribute : Attribute, EnumHelper.IAttribute<int>
{
private readonly int _value;

public PriorityLevelAttribute(int value)
{
_value = value;
}

public int Value
{
get { return _value; }
}
}

Another think that I thought would be quite good was to have a strong type attribute for enums.
This extension method will allow you to return a strong type value of your attribute enum value.

/// <summary>
/// Returns the attribute value for a given Enum value.
/// </summary>
public static TR GetAttributeValue<T, TR>(this Enum value)
{
var attributeValue = default(TR);

if (value != null)
{
var fi = value.GetType().GetField(value.ToString());

if (fi != null)
{
var attributes = fi.GetCustomAttributes(typeof(T), false) as T[];

if (attributes != null && attributes.Length > 0)
{
var attribute = attributes[0] as IAttribute<TR>;

if (attribute != null)
{
attributeValue = attribute.Value;
}
}
}
}

return attributeValue;
}

Imagine you have a enum class, and you wanted to have addition information to the enum.
This is a elegant way to implement a strong type value for your enum, throught attribute.

public enum League
{
[DisplayDescription("Argentine Primera Division")]
PrimeraDivision = 1,

[DisplayDescription("English Premier League")]
PremierLeague = 2,

[DisplayDescription("Spanish La Liga")]
LaLiga = 3
}

public class DisplayDescriptionAttribute : Attribute, EnumHelper.IAttribute<string>
{
private readonly string _value;

public DisplayDescriptionAttribute(string value)
{
_value = value;
}

public string Value
{
get { return _value; }
}
}

/// <summary>
/// This is the implementation.
/// </summary>
var displayValue = league.GetAttributeValue<DisplayDescriptionAttribute, string>();

Filter Combo Box

Please let me know if this helps you.