当前位置: 首页 > 编程语言 > C#

WPFDatagrid:以编程方式编辑单元格Share

时间:2023-04-11 00:46:29 C#

WPFDatagrid:以编程方式编辑单元格我有一个单元格需要在单击时设置其值。它有多个具有不同属性的绑定。我应该在哪里做这个?我一直在尝试在数据网格beginningedit处理程序中执行此操作(但没有取得太大成功)。我可以手动点击两次(一次选择单元格,然后开始编辑),然后设置值。但我想以编程方式做到这一点……privatevoidMyDataGrid_BeginningEdit(objectsender,DataGridBeginningEditEventArgse){如果(t==null)返回;t.Text=SimulatedEdit();//下面所有这些只是我尝试不同的东西。不确定我需要做什么e.EditingEventArgs.Handled=true;MyDataGrid.CommitEdit();MyDataGrid.UnselectAllCells();}这就是设置列模板的方法MultiBindingtempmb=newMultiBinding();绑定tempXB=newBinding("X");绑定temptYB=newBinding("Y");tempmb.Bindings.Add(tempXB);tempmb.Bindings.Add(tempYB);tempmb.ConverterParameter="ggrid";tempmb.Converter=newLabelDecider();DataGridTemplateColumndgtc=newDataGridTemplateColumn{Header="blah",CanUserSort=false,CanUserReorder=false,};DataTemplatet=newDataTemplate();FrameworkElementFactoryf=newFrameworkElementFactory(typeof(TextBlock));f.SetBinding(TextBlock.TextProperty,tempmb);//设置背景颜色绑定MultiBindingcolorb=newMultiBinding();colorb.Bindings.Add(tempX);colorb.Bindings.Add(tempY);colorb.ConverterParameter="颜色";colorb.Converter=newLabelDecider();f.SetBinding(TextBlock.BackgroundProperty,colorb);t.VisualTree=f;//每列Text和Background都使用绑定dgtc.CellTemplate=t;//设置编辑模板DataTemplateced=newDataTemplate();FrameworkElementFactoryf2=newFrameworkElementFactory(typeof(TextBox));MultiBindingtempmb2=newMultiBinding();tempmb2.Bindings.Add(tempXB);tempmb2.Bindings.Add(tempYB);tempmb2.Mode=BindingMode.TwoWay;tempmb2.ConverterParameter="ggrid";tempmb2.Converter=newLabelDecider(rDestination.Recievers[k]);tempmb2.UpdateSourceTrigger=UpdateSourceTrigger.LostFocus;f2.SetBinding(TextBox.TextProperty,tempmb2);ced.VisualTree=f2;dgtc.CellEditingTemplate=ced;我的数据网格。列。添加(dgtc);不确定我是否正确理解你的问题;看起来您想以编程方式访问和更改DataGridCell内容查看以下示例;我为数据网格添加了一个SelectedCellsChanged偶数处理程序,每次选择一个新单元格时都会触发它;有了DataGridCellInfo对象,您就可以访问DataGridCell对象并更改其内容。privatevoiddataGrid1_SelectedCellsChanged(objectsender,SelectedCellsChangedEventArgse){foreach(DataGridCellInfocellInfoindataGrid1.SelectedCells){//这改变了单元格的内容而不是它后面的数据项DataGridCellgridCell=TryToFindGridCell(dataGrid1,cellInfo);if(gridCell!=null)gridCell.Content="改变!!!";}}staticDataGridCellTryToFindGridCell(DataGridgrid,DataGridCellInfocellInfo){DataGridCellresult=null;DataGridRow行=(DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(cellInfo.Item);如果(行!=空){intcolumnIndex=grid.Columns.IndexOf(cellInfo.Column);如果(columnIndex>-1){DataGridCellsPresenterpresenter=GetVisualChild(row);结果=presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex)作为DataGridCell;}}返回结果;}staticTGetVisualChild(Visualparent)whereT:Visual{Tchild=default(T);intnumVisuals=VisualTreeHelper.GetChildrenCount(parent);对于(整数我=0;一世(五);}if(child!=null){break;}}返回孩子;GetVisualChild的代码取自此处希望对您有所帮助,您可能还想查看问题背后的代码查看特定Cell的BeginEdit我认为它也可以给您一些想法问候以上是C#学习教程:WPFDatagrid:EditingCellsProgrammatically分享所有内容,如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: