簡體   English   中英

使用 MVVM 在 WPF DataGrid CellEditEnding 事件中取消后將光標保持在單元格中

[英]Keep cursor in cell after cancel in WPF DataGrid CellEditEnding event with MVVM

我正在編輯的數據網格中有一個單元格。 當單元格編輯結束時,我在網格中使用 CellEditEnding 事件來捕獲它並進行一些驗證。 如果驗證失敗,我需要將光標留在該單元格中,而不是移動到下一個單元格。 正如您所看到的,我將取消設置為 true,但這只是將單元格保持在編輯模式,並且仍然讓光標移動到下一個單元格。 我需要一種方法將光標保持在單元格中,直到一切正常。

xml:

<DataGrid Style="{StaticResource ApplicationTabDataGridStyle}"
          ItemsSource="{Binding CurrentContacts, Mode=TwoWay}"
          SelectedValue="{Binding AddressGridItemSelected}"
          x:Name="ChangeInfoAddressGrid">

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="CellEditEnding">
            <command:EventToCommand PassEventArgsToCommand="True"
                                    Command="{Binding ValidateAddressRowCommand}"/>
    </i:EventTrigger>
    </i:Interaction.Triggers>
    <DataGrid.Columns>
        <DataGridTextColumn Header="Address 1" MinWidth="60"
                            Binding="{Binding Addr1, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                            IsReadOnly="{Binding Data.AddressGridItemSelected.CanEdit, 
                                                 Converter={StaticResource boolToOppositeBoolConverter}, 
                                                 Source={StaticResource IsReadyOnlyProxy}}">
            <DataGridTextColumn.EditingElementStyle>
                <Style TargetType="TextBox">
                    <Setter Property="MaxLength" Value="26" />
                </Style>
            </DataGridTextColumn.EditingElementStyle>
        </DataGridTextColumn>

    ...

    </DataGrid.Columns>
</DataGrid>

C#

public RelayCommand<object> ValidateAddressRowCommand => new RelayCommand<object>(ValidateAddressRow);
private void ValidateAddressRow(object eventArgs)
{
    var cellEventArgs = eventArgs as DataGridCellEditEndingEventArgs;
    // DO SOME VALIDATION

    ...

    cellEventArgs.Cancel = true;     
    cellEventArgs.EditingElement.Focus();
}

我已經使用DataGrid_CellEditEnding事件處理程序完成了它並使用調度程序來達到目標​​(我有一個數據網格):

private void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    e.Cancel = true;
    (sender as DataGrid).Dispatcher.BeginInvoke((Action)(()=>
        {
            (sender as DataGrid).SelectedIndex = e.Row.GetIndex();
            e.EditingElement.Focus();
        }
    ));
}

您可以根據自己的需要進行調整。 我很困惑,您在 ViewModel 中使用了 View 類( DataGridCellEditEndingEventArgs )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM