1

ユーザーが Alt+X を押したときに DataGridTextColumn のキャレット位置にテキストを挿入するにはどうすればよいですか?

これがデータグリッドです

<DataGrid x:Name="TheGrid" SelectionUnit="Cell" ItemsSource="{Binding Soruce}"  AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        </DataGrid.Columns>
    </DataGrid>

独自の CellEditingTemplate と CellTemplate を作成しようとしました。しかし、そのようにすると、グリッドのタブ機能が台無しになります。次のセルを編集するには、タブを 2 回または 3 回押す必要があります。

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <TextBox Text="{Binding Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" KeyDown="TextBox_KeyDown"></TextBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=Value}"></TextBlock>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

コードビハインド。キャレットの位置を知る必要があるため、テキストをデータバインドされたモデルに直接挿入することはできません。

    private void TextBox_KeyDown(object sender, KeyEventArgs e)
    {
      //Insert text at caret position
    }
4

1 に答える 1

1

KeyDown イベントの EditingElementStyle に EventSetter を追加するスタイルを追加します。

<DataGrid x:Name="TheGrid" SelectionUnit="Cell" ItemsSource="{Binding Soruce}"  AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
            <DataGridTextColumn.EditingElementStyle>
                <Style TargetType="{x:Type TextBox}">
                    <EventSetter Event="KeyDown" Handler="TextBox_KeyDown" />
                </Style>
            </DataGridTextColumn.EditingElementStyle>
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

次に、イベント ハンドラーをコード ビハインドに追加します。SelectedText プロパティにテキストを挿入して慣れ親しんだ動作を取得し、挿入されたテキストの後にキャレットを移動します。

    private void TextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.SystemKey == Key.X && Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
        {
            string text = "Text to insert";
            TextBox textBox = sender as TextBox;
            textBox.SelectedText = text;
            textBox.SelectionStart = textBox.SelectionStart + text.Length;
            textBox.SelectionLength = 0;
        }
    }
于 2016-06-08T13:33:46.937 に答える