Как сделать возможность копировать текст с элемента в ListBox (WPF C#)
Есть 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 шт):
Если нужна возможность выделять мышью текст у объекта 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>
Так мы получим стандартное поведение, которое позволит выделить текст и скопировать его горячими клавишами:
Если нам надо копировать выделенный объект именно сочетанием клавиш, то для этого надо установить 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/.
Результат:

