Silverlight: Data-binding Enabled/Disabled Items on ComboBox

30days, Main Content Add comments

If you want to databind some class to the CombBoxBox in Silverlight you can run into a problem if you want to have some items disabled.

silverlight-disabled-combobox
When you add an ItemsSource all items are wrapped inside a ComboBoxItem. To access the IsEnabled property of the ComboBoxItem can be problematic.

In WPF you can set a style and apply it to the ComboBoxItem, but in Silverlight the Value of a Setter cannot be a Binding. The solution is to extend the ComboBox class itself and override the GetContainerForItemOverride method. This way we can insert our own ComboBoxItem with the additional binding in code:


namespace ExtendedComboBox
{
    public class BindableComboBox : System.Windows.Controls.ComboBox
    {
        protected override DependencyObject GetContainerForItemOverride()
        {
            ComboBoxItem cbi = new ComboBoxItem();
            // Bind using the "Enabled" property on the Animal class
            Binding enabledBinding = new Binding("Enabled");
            enabledBinding.Mode = BindingMode.OneWay;
            // Bind it to the IsEnabledProperty of the ComboBoxItem
            cbi.SetBinding(ComboBoxItem.IsEnabledProperty, enabledBinding);
            return cbi;
        }
    }
}

combobox.zip

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Bumpzee
  • del.icio.us
  • Facebook
  • Furl
  • Mixx
  • NewsVine
  • Reddit
  • StumbleUpon
  • YahooMyWeb
  • Google
WP Theme & Icons by N.Design Studio | SEO | Silver Cross Jewelry | Online Marketplace | B2B | Blogging | Barter | Entries RSS Comments RSS Log in