WPF Disable List Items with MVVM

I tried to find a lot of threads, and I found several that are pretty close, but not quite what I want. After a day of searching, I just decided to ask. I apologize if I missed something, I feel that it will be quite common, but I seem to be unable to get it.

I have a UserControl limited to a ViewModel and it has a Listbox with ItemsSource = ObservableCollection, which is a ViewModel property, as shown below:

Whenever I select an element, I call SomeObject.IsEnabled = false for several other elements depending on certain conditions. I would like to bind list items to this IsEnabled property so that I can highlight any items when I make a selection.

ViewModel:

Class ViewModel : PropertyNotificationObject { private ObservableCollection<SomeObject> m_list; public ObservableCollection<SomeObject> List {get; set;} //notifying properly private void selectedItem() { //several in SomeObjects in List sets IsEnabled = false } } 

Object class

 class SomeObject : PropertyNotificationObject { private bool m_isEnabled; public IsEnabled { get; set; } //notifying properly } 

Xaml

  <DataTemplate x:Key="ListTemplate"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <TextBlock Text="{Binding ., Converter={someConverterObjectToString}}"/> </Grid> </DataTemplate> <ListBox ItemsSource="{Binding List}" ItemTemplate="{StaticResource ListTemplate}"/> 

I tried using StyleTriggers on the ListBox.ItemContainerStyle and DataTemplate as shown below, but I could not figure out how to get to the SomeOject.IsEnabled property.

 <ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}"> <Style.Triggers> <DataTrigger Binding={???????? I can't get to my SomeObject properties.} </Style.Triggers> </Style> </ListBox.ItemContainerStyle> 

Sorry for the lack of colors, I'm new here and don't know how to use the editor well.

Thanks in advance.

+4
source share
1 answer

{Binding IsEnabled} in your ItemContainerStyle should do the job. Look at the VS debug window for binding errors

Change or directly bind the IsEnabled property of a ListBoxItem object:

 <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="IsEnabled" Value="{Binding IsEnabled}"/> </Style> 
+11
source

All Articles