0

Есть ListBox, в нем есть элементы, мне нужно сделать так, что бы текст элемента, который я выделил (т.е. нажал на него) копировался в буфер обмена при нажатии ctrl + c. Надеюсь понятно объяснил.

<Window x:Class="Encrypt.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:Encrypt"
    mc:Ignorable="d"
    Title="MainWindow" Height="600" Width="800" SizeToContent="Width">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width ="650"/>
        <ColumnDefinition Width ="*"/>
    </Grid.ColumnDefinitions>

    <StackPanel Grid.Column="1">
        <TextBlock Text="Ключ"/>
        <TextBox x:Name="CodeWord"/>
        <Button Content="Зашифровать" Click="EncryptButtonClick" Height="30"/>
        <Button Content="Дешифровать" Click="DescryptButtonClick" Height="30"/>
    </StackPanel>
    <StackPanel Grid.Column="0">
        <TextBox x:Name="InputText"/>
        <ListBox x:Name="OutputTextList"/>
    </StackPanel>
</Grid>
namespace Encrypt
{
public partial class MainWindow : Window
{
    Encryption encryption = new Encryption();
    Descyption descyption = new Descyption();


    public MainWindow()
    {
        InitializeComponent();
    }

    void EncryptButtonClick(object sender, RoutedEventArgs e)
    {
        ListBoxItem item = new ListBoxItem();
        item.Content = encryption.StartEncryption(InputText.Text, CodeWord.Text);
        OutputTextList.Items.Add(item);
    }

    void DescryptButtonClick(object sender, RoutedEventArgs e)
    {
        ListBoxItem item = new ListBoxItem();
        item.Content = descyption.StartDescryption(InputText.Text, CodeWord.Text);
        OutputTextList.Items.Add(item);
    }
}
}

Вот код, который связан с WPF. Это простая программа по шифровке. Вводишь Текст, кодовое слово, оно шифруется, и результат выводится в ListBox. Так выглядит сама программа введите сюда описание изображения

И я хочу узнать, как добавить возможность копировать текст выделенного элемента

1
  • Создайте минимальный пример на базе пустого приложения, покажите разметку и код. А так, InputBindings и SelectedItem вам помогут. Не заставляйте отвечающего писать код с нуля.
    – aepot
    28 окт 2020 в 17:11

1 ответ 1

1

Если нужна возможность выделять мышью текст у объекта ListBox, то его надо стилизовать под TextBox, задав ему привязку и режим IsReadOnly, примерно так:

<ListBox ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBox IsReadOnly="True" Text="{Binding Name, Mode=OneWay}" Background="Transparent" BorderThickness="0" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Так мы получим стандартное поведение, которое позволит выделить текст и скопировать его горячими клавишами:

Result 1

Если нам надо копировать выделенный объект именно сочетанием клавиш, то для этого надо установить InputBindings, который будет привязывать сочетание клавиш к команде и уже разметка будет такой:

<ListBox ItemsSource="{Binding Items}" IsSynchronizedWithCurrentItem="True">
    <ListBox.InputBindings>
        <KeyBinding Modifiers="Ctrl" Key="C"
            Command="{Binding CopyCommand}" CommandParameter="{Binding Items/}" />
    </ListBox.InputBindings>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Обратите внимание на IsSynchronizedWithCurrentItem, это позволяет получить текущий выбранный элемент при помощи простого Items/.
Результат:

Result 2

1

Ваш ответ

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

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