An old question, but there is no answer. You can do this with code by manipulating the selected item and index, but it is ugly and cumbersome. Instead, do it declaratively (XAML path!) With your related elements.
First you need a ViewModel with a list of items. Each element requires (at a minimum) a property to display and a property to determine whether the element is included or not.
Here's an example view model for one item in a list:
class MyViewModel : ViewModelBase { private string _title; public string Title { get { return _title; } set { if(value == _title) return; _title = value; RaisePropertyChanged("Title"); } } private bool _isEnabled; public bool IsEnabled { get { return _isEnabled; } set { if(value == _isEnabled) return; _isEnabled = value; RaisePropertyChanged("IsEnabled"); } } }
The above example assumes that MVVM Light is for ViewModelBase and the RaisePropertyChanged method, but you can do this using IPropertyNotified (or any other MVVM library).
You will then have a markup list similar to the following:
<ListBox ItemsSource="{Binding MyItems}"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <ContentPresenter IsHitTestVisible="{Binding IsEnabled}"/> </ControlTemplate> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Title}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
What is it. Now just load some viewmodel with a list of elements:
MainViewModel.MyItems = new ObservableCollection<MyViewModel>(); MainViewModel.MyItems.Add(new MyViewModel { Title = "Star Wars", IsEnabled = true }); MainViewModel.MyItems.Add(new MyViewModel { Title = "The Sound of Music", IsEnabled = false }); MainViewModel.MyItems.Add(new MyViewModel { Title = "Aliens", IsEnabled = true }); MainViewModel.MyItems.Add(new MyViewModel { Title = "Debbie Does Dallas", IsEnabled = false }); MainViewModel.MyItems.Add(new MyViewModel { Title = "True Grit", IsEnabled = false });
In this example, only science fiction films are available.
Hope this helps.
source share