Treeview右键单击选择

时间:2017-03-30 11:47:12

标签: c# wpf xaml mvvm treeview

所以我的问题一目了然,我想要TreeView的鼠标右键选择一个项目。我正在使用带有XAML和C#的WPF。

您可能会认为这并不太难 - 只需将右键单击事件附加到树视图中,将e.Source作为TreeViewItem投射,然后使用“IsSelected”属性进行播放。

就是这么简单,但我正在使用MVVM方法,所以e.Source和类似的东西都会从我的视图模型中获取信息。

我将提供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>

所以我在这一点上有点失落。我的目标是右键单击上下文菜单也选择一个项目(如在Windows资源管理器中)。

感谢阅读。

0 个答案:

没有答案