0

Всем привет у меня есть такой файловый менеджер, я указываю директорию в которой виду поиск и отображаю элементы в директориях в виде древа, я хочу выбирать узел из дерева и по нажатию правой кнопки мыши вызывалось ContextMenu,в котором я буду выполнять какие то действия. (Например копировать путь к вайлу) Как такое делать ? введите сюда описание изображения

<Window x:Class="FileSearch.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FileSearch"
        mc:Ignorable="d"
        Title="Seeker" Height="900" Width="880" Background="#FFBBD9DE" MinWidth="415" MinHeight="553"
        >
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10*"/>
            <ColumnDefinition Width="145*"/>
            <ColumnDefinition Width="5*"/>
            <ColumnDefinition Width="5*"/>
            <ColumnDefinition Width="75*"/>
            <ColumnDefinition Width="75*"/>
            <ColumnDefinition Width="5*"/>
            <ColumnDefinition Width="5*"/>
            <ColumnDefinition Width="50*"/>
            <ColumnDefinition Width="5*"/>
            <ColumnDefinition Width="5*"/>
            <ColumnDefinition Width="45*"/>
            <ColumnDefinition Width="7*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="10*"/>
            <RowDefinition Height="40*"/>
            <RowDefinition Height="770*"/>
            <RowDefinition Height="20*"/>
            <RowDefinition Height="30*"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TreeView Name="FolderView" Margin="0,10,0,0" Grid.Row="2" Grid.ColumnSpan="13" Grid.RowSpan="1">
            <TreeView.Resources>
                <Style TargetType="{x:Type TreeViewItem}">
                    <Setter Property="IsExpanded" Value="True" />
                </Style>
                <HierarchicalDataTemplate 
                    DataType="{x:Type local:FileNode}" 
                    ItemsSource="{Binding Items}">
                    <StackPanel Orientation="Horizontal">
                        <Image Height="16" Margin="0,1,3,1" 
                               Source="\Images\file.png" 
                               Width="16" />
                        <TextBlock Text="{Binding NodeName}" />
                    </StackPanel>
                </HierarchicalDataTemplate>
                <HierarchicalDataTemplate 
                    DataType="{x:Type local:DirectoryNode}" 
                    ItemsSource="{Binding Items}">
                    <StackPanel Orientation="Horizontal">
                        <Image Height="16" Margin="0,1,3,1"
                               Source="\Images\folder-closed.png" 
                               Width="16" />
                        <TextBlock 
                            VerticalAlignment="Center" 
                            Text="{Binding NodeName}" />
                    </StackPanel>
                </HierarchicalDataTemplate>
            </TreeView.Resources>
        </TreeView>
        <Button Name ="Seek_Button" Content="Поиск" Grid.Column="8" HorizontalAlignment="Left" Margin="10,0,0,0" Grid.Row="1" VerticalAlignment="Bottom" Width="90" Height="40" Background="#FFA2A2A2" Click="Seek_Button_Click" RenderTransformOrigin="0.444,0.25"/>
        <Button x:Name ="Stop_Button" Content="Остановить" Grid.Column="11" HorizontalAlignment="Left" Grid.Row="1" VerticalAlignment="Bottom" Width="90" Height="40" Background="#FFA2A2A2" Click="Stop_Button_Click"/>
        <TextBox Name ="tb_filter"  Grid.Column="4" HorizontalAlignment="Left" Height="40" TextWrapping="Wrap" VerticalAlignment="Top" Width="300" Grid.Row="1" Grid.ColumnSpan="2" FontSize="16"/>
        <TextBox Name ="tb_start_dir"  Grid.Column="1" HorizontalAlignment="Left" Height="40" TextWrapping="Wrap" VerticalAlignment="Top" Width="290" Grid.Row="1" FontSize="16"/>
        <TextBlock Grid.Column="1" HorizontalAlignment="Left" Grid.Row="3" TextWrapping="Wrap" Text="Current Directory :" VerticalAlignment="Top" Width="290" Cursor="Help" FontSize="16" Height="21" Grid.RowSpan="2"/>
        <TextBlock Grid.Column="4" HorizontalAlignment="Left" Grid.Row="3" Grid.RowSpan="2" TextWrapping="Wrap" Text="Found : " VerticalAlignment="Top" Width="150" Height="21" FontSize="16" Cursor="Help"/>
        <TextBlock Grid.Column="5" HorizontalAlignment="Left" Grid.Row="3" Grid.RowSpan="2" TextWrapping="Wrap" Text="All found : " VerticalAlignment="Top" Width="150" Height="21" FontSize="16" Cursor="Help"/>
        <TextBlock Text="{Binding Path=Found, UpdateSourceTrigger=PropertyChanged}" Name ="tb_found" Grid.Column="4" HorizontalAlignment="Left" Margin="0,1,0,0" Grid.Row="4" Grid.RowSpan="2" TextWrapping="Wrap" VerticalAlignment="Top" Height="30" Width="150" FontSize="20"/>
        <TextBlock Text="{Binding Path=AllFound, UpdateSourceTrigger=PropertyChanged}" Name ="tb_all_found" Grid.Column="5" HorizontalAlignment="Left" Margin="0,1,0,0" Grid.Row="4" TextWrapping="Wrap" VerticalAlignment="Top" RenderTransformOrigin="-0.612,0.313" Width="150" Height="29" FontSize="20"/>
        <TextBlock Text="{Binding Path=CurrentDiretory, UpdateSourceTrigger=PropertyChanged}" Grid.Column="1" HorizontalAlignment="Left" Margin="0,1,0,0" Grid.Row="4" TextWrapping="Wrap" VerticalAlignment="Top" Width="290" Height="29" FontSize="10"/>
        <TextBlock Grid.Column="8" HorizontalAlignment="Left" Grid.Row="3" Grid.RowSpan="2" TextWrapping="Wrap" VerticalAlignment="Top" RenderTransformOrigin="0,0.312" Width="210" Grid.ColumnSpan="4" Height="21" FontSize="16"><Run Text="Spend time :"/><LineBreak/><Run/></TextBlock>
        <TextBlock Text="{Binding Path=SpendTime, UpdateSourceTrigger=PropertyChanged}" Grid.Column="8" HorizontalAlignment="Left" Margin="0,1,0,0" Grid.Row="4" TextWrapping="Wrap" VerticalAlignment="Top" Width="210" Grid.ColumnSpan="4" Height="29" FontSize="16"/>
    </Grid>
</Window>

1
  • В <TreeView.Resources> добавьте ContextMenu, назначьте ему x:Key, и у текстблоков подключите его по этому ключу ContextMenu="{StaticResource MyKey}" как-то так, но я не помню, как точно это делается именно для вашего случая. Пример, Еще пример
    – aepot
    7 мар 2021 в 20:59

1 ответ 1

1

Например, так.

<HierarchicalDataTemplate 
    DataType="{x:Type local:FileNode}" 
    ItemsSource="{Binding Items}">
    <StackPanel Orientation="Horizontal">
        <StackPanel.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Copy path" Command="{Binding CopyCommand}"/>
                <MenuItem Header="Delete file" Command="{Binding DeleteCommand}"/>
            </ContextMenu>
        </StackPanel.ContextMenu>
        <Image Height="16" Margin="0,1,3,1" 
               Source="\Images\file.png" 
               Width="16" />
        <TextBlock Text="{Binding NodeName}" />
    </StackPanel>
</HierarchicalDataTemplate>

Вам придётся определить команды CopyCommand и DeleteCommand в вашем FileNode. Это можно сделать, к примеру, так:

class FileNode : Node
{
    public ICommand CopyCommand { get; }
    public ICommand DeleteCommand { get; }
    public FileNode()
    {
        CopyCommand = new SimpleCommand(OnCopy);
        DeleteCommand = new SimpleCommand(OnDelete);
    }
    void OnCopy()
    {
        // ...
    }
    void OnDelete()
    {
        // ...
    }
}

class SimpleCommand : ICommand
{
    readonly Action onCommand;
    public SimpleCommand(Action onCommand) => this.onCommand = onCommand;

    public event EventHandler CanExecuteChanged;
    public bool CanExecute(object parameter) => true;
    public void Execute(object parameter) => onCommand();
}

Результат:

картинка

2
  • Круто ! Вижу а мы SRP не нарушаем ? Если нарушаем, то как делать надо ? 9 мар 2021 в 16:30
  • @Samsongoot: Ну, я не знаю, какая архитектура у башего приложения. С другой стороны, команду можно навесить и на корневой элемент, и всякие операции пусть делает он сам, например. Соответственно у вас поменяется и привязка.
    – VladD
    9 мар 2021 в 18:35

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.