I would suggest defining the SelectItem command in the main ViewModel, which takes the element to be selected as a parameter. Then, the method for executing this command can set the MySelectedItem property, set the IsSelected property in the ViewModel to true and call all further actions of the element itself (that is, what MyCommand is now executing). With the selection logic in the ViewModel and pure binding, you donโt need to use a ListView , but you can stick with a simple ItemsControl :
Then XAML looks like this:
<ItemsControl ItemsSource="{Binding MyItemSource}"> <ItemsControl.ItemTemplate> <DataTemplate> <Expander IsExpanded="{Binding IsSelected}"> <Expander.Header> <Button Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ItemsControl}, Path=DataContext.SelectItem}" CommandParameter="{Binding"}>Click Me</Button> </Expander.Header> </Expander> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>
MainViewModel will look something like this:
public class MainViewModel : INotifyPropertyChanged { public ObservableCollection<ItemViewModel> MyItemsSource { get; private set; } public ItemViewModel SelectedItem { get... set... } public ICommand SelectItem { get; private set; } ctor()... private void ExecuteSelectItem(ItemViewModel item) { SelectedItem = item; foreach (var i in MyItemsSource) i.IsSelected = false; item.IsSelected = true; item.DoSomething(); } }
It has always been easier for me to use the ItemsControl implement several lines of selection logic myself, instead of dealing with the messy binding of the ListView selection. In my opinion, it is quite intuitively clear how to implement custom selection behavior (several elements that allow only certain combinations, etc.). You can easily use the IsSelected property to apply an individual style to selected elements.
source share