簡體   English   中英

刷新項目后如何在WPF DataGrid中恢復對單元格的關注

[英]How to restore focus on cell in WPF DataGrid after refresh of the items

我正在使用VS2015開發WPF應用程序。

為了驗證WPF數據網格中具有最小值和最大值的列,我使用ValidationRule。

這是ValidationRule的代碼:

public class MinMaxValidationRule : System.Windows.Controls.ValidationRule
{
    /// <summary>
    /// Validates updated values and compares min and max values.
    /// </summary>
    /// <param name="value"></param>
    /// <param name="cultureInfo"></param>
    /// <returns></returns>
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        BindingExpression bindingExpr = value as BindingExpression;
        if (bindingExpr != null)
        {
            var item = bindingExpr.DataItem as XraySystemStructure;
            if (item != null &&
                item.countMandatory > item.countMax)
            {
                // The min value is bigger than the max value -> disables the save-button and displays error
                SaveButtonEnabled = false;
                return new ValidationResult(false, TextCountMandatoryBiggerThanCountMax);
            }

            // Validation is correct -> Refreshes the datagrid to remove all errors (multiple datagridcells)
            SaveButtonEnabled = true;
            grdSystemStructure.Items.Refresh();
        }

        // Validation is correct -> Remove all errors
        return new ValidationResult(true, null);
    }
}

在驗證中,我正在檢查countMandatory中的值是否大於countMax中的值。

如果countMandatory較大,則錯誤。

在運行時,兩個單元都可能標記有validationerror,因為用戶可以在countMax中輸入一個小於countMandatory的值,該值是錯誤的。

所以-為了在驗證成功的情況下刪除-所有驗證錯誤我都必須對datagrid的所有項目使用刷新。

這樣一來,我就失去了對數據網格的關注,因此用戶必須單擊該單元格才能在當前單元格中繼續其輸入。

例如:

用戶輸入了countMandatory“ 2”和maxCount“ 1”。

maxCount列標記有驗證錯誤。

然后,用戶希望將maxCount編輯為“ 111”,單擊maxCount單元格並添加另一個“ 1”,以便maxCount現在為“ 11”,並且驗證成功。

但是通過刷新項目,數據網格失去了焦點,用戶必須在單元格中用鼠標單擊才能繼續最后一個對用戶不友好的“ 1”。

如何恢復對當前單元格的關注? 我嘗試在刷新后設置SelectedItem和CurrentCell,但是它不起作用。

每個例子都不能解決我的問題的解決方案:

            grdSystemStructure.Items.Refresh();
            grdSystemStructure.ScrollIntoView(item, column);
            grdSystemStructure.CurrentCell = new DataGridCellInfo(selItem, column);
            grdSystemStructure.BeginEdit();
            grdSystemStructure.Focus();

任何幫助,將不勝感激。

您必須首先設置數據網格的當前單元格,然后調用BeginEdit方法以使鍵盤焦點位於該單元格內。

dataGrid1.Focus();
DataGridCellInfo cellInfo = new DataGridCellInfo(itemCollection2.First(), dataGrid1.Columns[0]);
dataGrid1.CurrentCell = cellInfo;
dataGrid1.ScrollIntoView(itemCollection2.First());
dataGrid1.BeginEdit();

我已經對此進行了測試,並且可以正常工作,在刷新網格項目之后,首先將焦點設置到網格上。

PS:請按照上述方法調用的順序進行。

暫無
暫無

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

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