轉(zhuǎn)帖|其它|編輯:郝浩|2011-03-21 11:50:56.000|閱讀 8266 次
概述:WPF DataGrid中自定義列DataGridTemplateColumn非常的方便,但是假如其中有控件,要在后臺cs代碼中獲取嵌入的控件,則非常困難。本來以為非常簡單的一個工作,沒想到如此復(fù)雜,查了好多資料,研究了好長時間才搞出來,可能這個方法太過于復(fù)雜,應(yīng)該還有很簡單的獲取的方法的,期待更簡單的方法吧:
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
WPF DataGrid中自定義列DataGridTemplateColumn非常的方便,但是假如其中有控件,要在后臺cs代碼中獲取嵌入的控件,則非常困難。本來以為非常簡單的一個工作,沒想到如此復(fù)雜,查了好多資料,研究了好長時間才搞出來,可能這個方法太過于復(fù)雜,應(yīng)該還有很簡單的獲取的方法的,期待更簡單的方法吧:
實現(xiàn)思路如下:根據(jù)行號和列號,獲取DataGridCell 對象,然后根據(jù)DataGridCell對象進行查找。
使用方法:
假如在DataGridTemplateColumn的<DataTemplate>中第0列有一個Name="txtContent"的TextBlock,在后臺cs代碼中如此獲取。
此控件位于DataGrid選中的這一行的第0列。
MessageBox.Show(FindCellControl<TextBlock>("txtContent").Text);
public T FindCellControl<T>(string name) where T : Visual
{
DataRowView selectItem = dataGrid.SelectedItem as DataRowView;
DataGridCell cell = GetCell(dataGrid, dataGrid.SelectedIndex, 0);
return FindVisualChildByName<T>(cell, name) as T;
}
public T FindVisualChildByName<T>(Visual parent, string name) where T : Visual
{
if (parent != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i) as Visual;
string controlName = child.GetValue(Control.NameProperty) as string;
if (controlName == name)
{
return child as T;
}
else
{
T result = FindVisualChildByName<T>(child, name);
if (result != null)
return result;
}
}
}
return null;
}
public static DataGridCell GetCell(DataGrid datagrid, int rowIndex, int columnIndex)
{
DataGridRow rowContainer = GetRow(datagrid, rowIndex);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
if (cell == null)
{
datagrid.ScrollIntoView(rowContainer, datagrid.Columns[columnIndex]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
}
return cell;
}
return null;
}
public static DataGridRow GetRow(DataGrid datagrid, int columnIndex)
{
DataGridRow row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromIndex(columnIndex);
if (row == null)
{
datagrid.UpdateLayout();
datagrid.ScrollIntoView(datagrid.Items[columnIndex]);
row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromIndex(columnIndex);
}
return row;
}
public static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉(zhuǎn)載自:網(wǎng)絡(luò)轉(zhuǎn)載