So my problem at a glance is that I want the right mouse button of my TreeView to select an item. I'm using WPF with XAML and C#.
That's not too hard, you might think - just attach a right click event to the treeview, cast the e.Source as a TreeViewItem and then play with the 'IsSelected' property.
And it would be that simple, but I'm using the MVVM approach so e.Source and things like that come back with information from my view model.
I'll provide the XAML:
<TreeView x:Name="ScenesTreeView01" Grid.Column="0" Width="Auto" Background="AliceBlue" ItemsSource="{Binding Scenes}" SelectedItemChanged="TreeView_SelectedItemChanged" BorderThickness="0">
<TreeView.DataContext>
<viewModels:ScenesViewModel />
</TreeView.DataContext>
<TreeView.Resources>
<ContextMenu x:Key="SceneLevel">
<MenuItem Header="Add selected character" Command="{Binding Path=DataContext.AddSelectedCharacter, Source={x:Reference ScenesTreeView01}}"/>
</ContextMenu>
<ContextMenu x:Key="CharacterLevel">
<MenuItem Header="Remove character from scene" Command="{Binding Path=DataContext.RemoveCharacterFromScene, Source={x:Reference ScenesTreeView01}}"/>
</ContextMenu>
</TreeView.Resources>
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="BorderThickness" Value="1.5"/>
<Style.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="5"/>
</Style>
</Style.Resources>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Characters}">
<StackPanel Orientation="Horizontal" ContextMenu="{StaticResource SceneLevel}">
<TextBlock Text="{Binding SceneName}"></TextBlock>
<Image Source="{StaticResource ImgBook1}" Margin="0,0,5,0" Width="32" Height="32"/>
</StackPanel>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<Border BorderThickness="2" BorderBrush="LightBlue" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="2" CornerRadius="5,5,5,5">
<StackPanel Orientation="Horizontal" Margin="3" ContextMenu="{StaticResource CharacterLevel}">
<TextBlock FontFamily="Levenim MT" FontSize="16" VerticalAlignment="Center" MinWidth="50" Text="{Binding FirstName}"></TextBlock>
<Image Source="{Binding ImgIcon}" Margin="2" Width="32" Height="32"/>
</StackPanel>
</Border>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
So I'm a little bit lost on this one. My aim is to have the right click for context menu also select an item (like in Windows Explorer).
Thanks for reading.