Databinding a nullable value to a combobox lookup – Silverlight – The Missing Notes
(This is a series of unspoken Silverlight best practices, designed to avoid specific pain points when developing Silverlight applications. Refer to this URL http://www.redmountainsw.com/wordpress/?p=1270#list for a complete listing).
Scenario
You have a field CountryID which could be set to null. If you set the ComboBox.ItemsSource=Countries then the user could not select a null value.
Another scenario is you want to present a filter of a list of countries. However, one of the items have be to “(Show all)”.
Solution
Use a NullableItemsSource (code below). The usage is like this:
this.LookupCountries = new Helpers.NullableItemsSource(
from c in this._context.Countries orderby c.CountryName select c,
new Country { CountryID=0, CountryName = "(None)" });
namespace ProjectNavigation.Helpers
{
using System.Collections;
public class NullableItemsSource : IEnumerable
{
#region Constructor
public NullableItemsSource(IEnumerable ItemsSource, object NullItem)
{
m_NullDisplayListItem = NullItem;
this.m_ItemsSource = ItemsSource;
}
public object First
{
get
{
IEnumerator it = GetEnumerator();
it.MoveNext();
return it.Current;
}
}
#endregion
#region Private members
private IEnumerable m_ItemsSource;
private object m_NullDisplayListItem;
#endregion
public IEnumerable ItemsSource
{
get { return m_ItemsSource; }
set { m_ItemsSource = value; }
}
public IEnumerator GetEnumerator()
{
yield return m_NullDisplayListItem;
foreach (var item in m_ItemsSource)
{
yield return item;
}
}
}
}
About this entry
You’re currently reading “ Databinding a nullable value to a combobox lookup – Silverlight – The Missing Notes ,” an entry on Chui's Counterpoint
- Published:
- 11.26.11 / 5am
- Category:
- .Net, Silverlight
Comments are closed
Comments are currently closed on this entry.