首页 > 解决方案 > 如何在 WPF DataGrid 中禁用 CTRL 键盘

问题描述

我有一个数据网格,我想在其中阻止用户按 CTRL 键。

<ImageBrush ImageSource="/AB17035_ZLT_Client;component/Images/bum_big.PNG"
                                Stretch="Uniform" Opacity="0.05" />
        </Border.Background>
        <DataGrid Name="PlanGrid" HorizontalAlignment="Stretch" FontSize="16" RowHeight="30" HorizontalScrollBarVisibility="Visible"
            VerticalAlignment="Stretch"
            AutoGenerateColumns="True"
            SelectionMode="Extended" 
            VerticalGridLinesBrush="Transparent"
            Background="Transparent" RowBackground="Transparent"
            ItemsSource="{Binding PlanDataView, Mode=TwoWay}"
            IsReadOnly="True" SelectionUnit="FullRow" IsSynchronizedWithCurrentItem="True" Cursor="Arrow" AllowDrop="True">
            <DataGrid.InputBindings>
                <KeyBinding Gesture="Ctrl" Command="ApplicationCommands.NotACommand"></KeyBinding>
            </DataGrid.InputBindings>
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Loaded">
                    <ei:CallMethodAction MethodName="PlanGrid_Loaded" TargetObject="{Binding}"></ei:CallMethodAction>                        
                </i:EventTrigger>
            </i:Interaction.Triggers>                
        </DataGrid>

如果用户尝试按下 CTLR 键,它不应该在 wpf 数据网格上工作。

标签: datagrid

解决方案


我用谷歌搜索并找到了答案。下面是防止按 ctrl 键的一段代码。

private void PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {                
                e.Handled = true;                
                MessageBox.Show("CTRL Key is not allowed");
            }
        }

还添加此功能“PreviewKeyDown”来加载数据网格的事件,如下所示:

public void PlanGrid_Loaded(object sender, RoutedEventArgs e)
        {            
           planDatagrid.KeyDown += new KeyEventHandler(PreviewKeyDown);               
        }

推荐阅读