------------------
首先不推薦這種模式
ItemsSource 已經綁定了源. Items 集合的數量變化很隨機, 每個儲存格的控制項取決於
預設的DataTemplate(設定 DisplayMemberBinding 時) 或者
CellTemplate 定義的控制項, 或者
CellTemplateSelector 指定的 Template 定義的控制項.
通過 rowIndex 和 cellIndex 來取得某儲存格控制項其實不是好的解決問題的辦法. 你完全可以在資料層面上捕抓到改變, 然後根據改變後的值判斷是否應該採用新值, 而不應在 UI 元素上下功夫.
------------------
回到問題,
如何取得在儲存格中承載資料的控制項? (這裡所說的儲存格是指, ListView 的 View 是 GridView 或其衍生類 的某一個承載資料的東西).
要取得, 必須要瞭解. ListView 是一種 Items 的控制項, 它的每一個 Item 都由 ListViewItem 作為容器來承載它要顯示的內容.
ListView
ListViewItem1
ListViewItem2
...
即使在 DataTemplate 沒有使用 ListViewItem , ListView 顯示時也使用 ListViewItem 來承載它. 對於使用 GridView 的 ListView 來說, 每一個 ListViewItem 的控制項樹結構就像下面所示的:
ListViewItem (default, non-styled)
Border
GridViewRowPresenter
ContentPresenter 1
承載資料所用的控制項1 (你問題的目標控制項就是這個了, 儲存格1)
ContentPresenter 2
承載資料所用的控制項2 (儲存格2)
...
ContentPresenter N
承載資料所用的控制項N (儲存格N)
顯然, ContentPresenter 的 Content 正是我們目標所要得到的東西.
於是有了下面的函數:
private UIElement GetListViewCellControl(int rowIndex, int cellIndex)
{
// rowIndex 和 cellIndex 基於 0.
// 首先應得到 ListViewItem, 毋庸置疑, 所有可視UI 元素都繼承了UIElement:
UIElement u = lv.ItemContainerGenerator.ContainerFromIndex(rowIndex) as UIElement;
if(u==null) return null;
// 然後在 ListViewItem 元素樹中搜尋 儲存格:
while ((u=(VisualTreeHelper.GetChild(u, 0) as UIElement)) != null)
if (u is GridViewRowPresenter) return VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(u, cellIndex), 0) as UIElement;
return u;
}
這個函數就返回了儲存格的控制項, 是 UIElement, 對應的, 如果你 DataTemplate 是使用 TextBox 承載資料的, 它的傳回值就是一個 TextBox, 如果你用 CheckBox 承載資料, 它的傳回值就是一個 CheckBox, and so on, 例如:
TextBox t = GetListViewCellControl(1, 2) as TextBox; // 第2 行,第3 格
CheckBox t = GetListViewCellControl(3, 4) as CheckBox; // 第4 行第 5 格
...
總言, 這是一種不好的方式, 這種方式使用了 WinForm 的模式來操縱資料, 它並不適合 wpf.