public void MouseSingleClickEditable(object sender, MouseButtonEventArgs e)
{
if ((!datagrid.HasItems) || datagrid.SelectedIndex < 0) return;
DataGridColumn clmn = datagrid.CurrentColumn;
if (clmn != null)
{
String columnType = clmn.GetType().Name;
switch (columnType)
{
case "DataGridTemplateColumn":
case "DataGridCheckBoxColumn":
row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromItem(datagrid.Items[datagrid.SelectedIndex]);
if (!row.IsEditing)
{
datagrid.IsReadOnly = false;
datagrid.BeginEdit();
}
break;
default:
break;
}
}
}
我的WPF Datagrid中有2个DatePickers,Checkbox和一个组合框,但在对列类型进行geeting时,我只将其作为DataGridTemplateColumn而不是DataGridDatePickerColumn或DataGridComboboxColumn类型。如何从DataGridTemplateColumn中提取确切的Control类型。
答案 0 :(得分:1)
public void MouseSingleClickEditable(object sender, MouseButtonEventArgs e) {
var datagrid = new DataGrid();
if ((!datagrid.HasItems) || datagrid.SelectedIndex < 0) return;
DataGridColumn clmn = datagrid.CurrentColumn;
if (clmn != null) {
if (clmn is DataGridCheckBoxColumn) {
//do something
} else if (clmn is DataGridTemplateColumn) {
var templateColumn = (DataGridTemplateColumn)clmn;
var rootControlOfCellTemplate = templateColumn.CellTemplate.LoadContent();
var rootControlOfCellEditingTemplate = templateColumn.CellEditingTemplate.LoadContent();
// you can now check for types of the template. CellEditingTemplate is for template in edit mode, and CellTemplate for "non-edit" mode
// for example
if (rootControlOfCellTemplate is Button) {
//do something
}
if (rootControlOfCellEditingTemplate is DatePicker) {
//do something
}
}
}
}
请注意我如何检查类型。通常你应该这样做,而不是用硬编码的字符串。