Making a combobox certain items non-selectable in Silverlight 4


Hi there,
Few days ago i ran into situation where i have to make some items of combobox non-selectable, I browsed and found solution for Silverlight 5 but i have to do it in Silverlight 4 so i did some modification and it works.


Combobox needs to be bind to a data source, i bind mine to ObservableCollection. As ObservableCollection needs a type so i defined a custom class to fulfill my requirements. That class is written below.

public class clsCheckedListBox
        public Boolean IsChecked { get; set; }

        public String Value { get; set; }

        public String Text { get; set; }

        /// <summary>
        /// Constructor for clsCheckedListBox
        /// </summary>
        public clsCheckedListBox(Boolean ischecked, String value, String text)
            IsChecked = ischecked;
            Value = value;
            Text = text;

        /// <summary>
        /// Default Constructor
        /// </summary>
        public clsCheckedListBox()

Now we need a style that will perform the task for us, you can write in-line as well as doc-level style based on your need. I write an in-line style here.
You need to paste below line inside <ComboBox></ComboBox> tag.

                <Style TargetType="ComboBoxItem">
                    <Setter Property="Common:SetterValueBindingHelper.PropertyBinding">
                            <Common:SetterValueBindingHelper Property="IsEnabled"
                                                             Binding="{Binding Path=IsChecked}" />

Above style will disable some items based on their flag status IsChecked, that i am setting in my view model.

In my view model when i receive data for this collection, before i assigned that data to observablecollection source, i set the flag IsChecked based on the values i received using LINQ.
I am getting my data from a service so the syntax may seems different to you, if you did not understand it let me know then i post the static collection for this purpose. Hope you will be able to understand it.
So in any method of your selection, in which you want to assign you datasource with data, paste the below code.

Statuses = new ObservableCollection<srvD01S030.clsCheckedListBox>(
                                (from row in e.Result[3]
                                 select new srvD01S030.clsCheckedListBox() { Text = row.Text, Value = row.Value, IsChecked = (row.Value.Trim() == "Lost" || row.Value.Trim() == "Disappear") ? false : true }));

e.Result[3] => basically it contains a collection of type clsCheckedListBox and you can replace it with your own collection.

What i was doing in above lines is that, make combobox item non-selectable if its value is Lost or Disappear, else make item selectable.

If you perform everything correctly, you'll get output like below:

Happy coding!

Popular Posts