gpt4 book ai didi

wpf - C+Ctrl KeyBinding 不会导致复制发生

转载 作者:行者123 更新时间:2023-12-04 14:17:56 26 4
gpt4 key购买 nike

我设置了ListBox像这样:

<ListBox ItemsSource="{Binding Logs, Mode=OneWay}" x:Name="logListView">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=.}">
<TextBlock.InputBindings>
<KeyBinding Key="C"
Modifiers="Ctrl"
Command="Copy"/>
</TextBlock.InputBindings>
<TextBlock.CommandBindings>
<CommandBinding Command="Copy"
Executed="KeyCopyLog_Executed"
CanExecute="CopyLog_CanExecute"/>
</TextBlock.CommandBindings>
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Command="Copy">
<MenuItem.CommandBindings>
<CommandBinding Command="Copy"
Executed="MenuCopyLog_Executed"
CanExecute="CopyLog_CanExecute"/>
</MenuItem.CommandBindings>
</MenuItem>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

如您所见,在模板中,每个 TextBlock有一个上下文菜单,允许用户复制文本。这行得通。

也在 TextBlock有一个 KeyBinding到 ctrl+c 和 CommandBinding复印。当我按 ctrl+c 方法 KeyCopyLog_Executed不执行。我已经用调试器检查过了。

我应该如何将 key 绑定(bind)到 TextBlock ?

最佳答案

这里有几个问题。

首先,KeyBindings仅当当前焦点元素位于 时才有效里面 定义 KeyBindings 的元素。在您的情况下,您有一个 ListBoxItem专注,但 KeyBindings在子元素上定义 - TextBlock .所以,定义一个 KeyBindingsTextBlock在任何情况下都不起作用,因为 TextBlock 无法获得焦点。

其次,您可能需要知道要复制什么,因此您需要将当前选择的日志项作为参数传递给 Copy命令。

此外,如果您定义 ContextMenuTextBlock元素只有在你右击 TextBlock 时才会打开。 .如果单击列表项的任何其他部分,它将不会打开。因此,您需要定义 ContextMenu在列表框项目本身上。

考虑到所有这些,我相信您正在尝试做的事情可以通过以下方式完成:

<ListBox ItemsSource="{Binding Logs, Mode=OneWay}"
x:Name="logListView"
IsSynchronizedWithCurrentItem="True">
<ListBox.InputBindings>
<KeyBinding Key="C"
Modifiers="Ctrl"
Command="Copy"
CommandParameter="{Binding Logs/}" />
</ListBox.InputBindings>

<ListBox.CommandBindings>
<CommandBinding Command="Copy"
Executed="CopyLogExecuted"
CanExecute="CanExecuteCopyLog" />
</ListBox.CommandBindings>

<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Command="Copy"
CommandParameter="{Binding}" />
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>

<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

这里我们定义一个 KeyBindingListBox本身并指定为 CommandParameter当前选择的列表框项目(日志条目)。
CommandBinding也在 ListBox 中定义级别,它是右键菜单和键盘快捷键的单一绑定(bind)。
ContextMenu我们在 ListBoxItem 的样式中定义并绑定(bind) CommandParameter到这个 ListBoxItem 表示的数据项(日志条目)。
DataTemplate只声明一个 TextBlock绑定(bind)到当前数据项。

最后, Copy 只有一个处理程序。代码隐藏中的命令:
private void CopyLogExecuted(object sender, ExecutedRoutedEventArgs e) {
var logItem = e.Parameter;

// Copy log item to the clipboard
}

private void CanExecuteCopyLog(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = true;
}

关于wpf - C+Ctrl KeyBinding 不会导致复制发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5041275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com