WPF DataGrid显示表格中编辑Check数据

WPF DataGrid显示中编辑数据Check

1、DataGrid显示数据选中后编辑

//xaml 在DataGrid中加入事件
BeginningEdit = "dataGrid_BeginningEdit" CellEditEnding = "dataGrid_CellEditEnding" selectionUnit = "Cell"
//cs文件中加code 
    string collumnName = "";
private void dataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
    collumnName = dataGrid.CurrentColumn.Header.Tostring();
}

private void dataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    string newValue = (e.EditingElement as TextBox).Text;
    int rowCount = this.getCellRow(dataGrid);
    if(collumnName == "LOCATION"){
        DataGridList[rowCount].LOCATION = newValue;
    }
    if(collumnName == "LOTTYPE"){
        DataGridList[rowCount].LOTTYPE = newValue;
    }
    if(collumnName == "QTY"){ //如果输入的数字需要Check
        if(checkIsNum(newValue) == false){ //验证newValue 如果不通过给初始值“0”
            newValue = "";
            DataGridList[rowCount].QTY = "0";
            this.DataGrid.DataContext = null;
            this.DataGrid.DataContext = DataGridList;
            return;
        }
        
        int nValue = 0;
        int waferQty = 0;
        int.TryParse(newValue, out nValue);
        int.TryParse(DataGridList[rowCount].oldQTY, out waferQty)
            if(nValue > waferQty){ //输入的数字大于当前行的oldQTY值,则报错
                ErrorBox errBox = new ErrorBox(this,"Invalid Data", false);//自定义公共控件
                errBox.Owner = this;
                errBox.ShowDialog();
                newValue = "0";
            }
        DataGridList[rowCount].QTY = newValue;
    }
    this.DataGrid.DataContext = null;
    this.DataGrid.DataContext = DataGridList;
}
private int getCellRow(DataGrid dg){
    int RowNum = 99;
    var cells = dg.SelectedCells;
    if(cells.Any()){ //集合中有任何一元素满足条件,返回就true 不带任何参数,表示集合中有元素
        			//如加参数委托,集合中有任何一个元素满足该条件就返回true
        RowNum = dg.Items.IndexOf(cells.First().Item);
    }
    return RowNum;
}
private bool checkIsNum(string str){
    Regex obj = new Regex(@"^[0-9]\d*$");
    return obj.IsMatch(str);
}

2、文本框限制只输入数字

//xaml定义事件
PreviewTextInput = "qty_textInput"
//cs Code
private void qty_textInput(){
    Regex re = new Regex(@"^[0-9]*$");
    e.Handled = !re.IsMatch(e.Text);
}    
posted @ 2021-01-20 16:12  DingGuo  阅读(335)  评论(0编辑  收藏  举报