Define some items in a ListBox as unselectable

It seems to be a quite common problem that one does not know how to set one or more items in a ListBox to unselectable or disabled.

The same principle as described here can also be user for similar problems like setting a different background color for some items.

First we’re going to create a simple domain class with a property that describes if the item should be selectable or not.

public class MyDataObject {
    public string Name { get; set; }
    public bool IsSelectable { get; set; }
}

Next we create a XAML Window that contains a ListBox. In this ListBox we define a custom ItemContainerStyle with a Style that defines if the Item will be selected or not. And finally we bind this Style to the IsSelectable property from our data object.


            

And now we just have to fill the ItemsSource from the ListBox and we can run the example.

public partial class MainWindow : Window {
    public MainWindow() {
        InitializeComponent();

        myListBox.ItemsSource =
            from i in Enumerable.Range(0, 10)
            select new MyDataObject() { Name = string.Format("Object {0}", i), IsSelectable = i % 3 != 0 };
    }
}

That’s all. Easy, isn’t it?

Comments (0)

› No comments yet.

Pingbacks (0)

› No pingbacks yet.