首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WPF DataGrid 進階:透過 Visual Tree 取得 Cell 與 IValueConverter 格式化綁定

     編輯:關於.NET

前言

WPF DataGrid 與 WinForms DataGridView 架構迥異:資料列為 DataGridRow,儲存格被封裝在 DataGridCellsPresenter 內,無法直接透過 Rows[i].Cells[j] 存取。本文示範如何透過 VisualTreeHelper 走訪視覺樹取得 DataGridCell,並詳解 IValueConverter 實現綁定資料格式化 (如路徑只顯示檔名)。

一、從 DataGrid 取得指定儲存格 (Visual Tree 走訪)

核心方法

DataGridRow rowContainer = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(rowIndex);
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
// 取得 cell.Content 或進一步操作

通用視覺樹搜尋遞迴函式

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);
        else break;
    }
    return child;
}

二、IValueConverter 實現綁定資料轉換

當資料來源屬性格式與顯示需求不符 (如完整路徑只想顯示檔名),實作 IValueConverter 在綁定管線中轉換。

範例:路徑轉檔名轉換器

using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;

class GetFileName : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        FileInfo fi = new FileInfo((string)value);
        return fi.Name; // 僅回傳檔名
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        throw new NotImplementedException(); // 單向綁定無需實作
    }
}

XAML 使用方式

  1. 宣告命名空間對應:xmlns:local="clr-namespace:YourNamespace"
  2. 在 Resources 建立實例:<local:GetFileName x:Key="GetFileName"/>
  3. 綁定時指定 Converter:
    <TextBlock Text="{Binding Path=FileName, Converter={StaticResource GetFileName}}" />
        <!-- 或完整語法 -->
        <TextBlock>
            <TextBlock.Text>
                <Binding Path="FileName">
                    <Binding.Converter><local:GetFileName/></Binding.Converter>
                </Binding>
            </TextBlock.Text>
        </TextBlock>

三、實務建議

  • 避免直接操作 Cell:WPF 鼓勵資料驅動 (MVVM),透過修改 ViewModel/資料來源屬性觸發 UI 更新,而非手動找 Cell 改內容。
  • Converter 單一職責:每個轉換器只做一件事 (路徑轉檔名、日期格式化、布林轉可見性),便於重用與測試。
  • 效能考量:VisualTreeHelper 走訪有開銷,大量資料時勿頻繁呼叫。虛擬化面板 (VirtualizingPanel) 下未實體化的列無法取得 Container。

總結

掌握 VisualTreeHelper 走訪技巧可解決特殊需求 (如儲存格級別的焦點管理、自訂編輯器定位),但日常開發應優先使用 IValueConverter 在綁定層處理格式化,符合 WPF 宣告式程式設計精髓。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved