前往
大廳
主題

在DataGridCell上雙擊後帶出所在的列所代表的資料

Yang | 2022-07-20 16:59:56 | 巴幣 10 | 人氣 269

以之前的AppLog舉例
XAML:
<DataGrid.Resources>
    <Style TargetType="{x:Type DataGridCell}">
        <EventSetter Event="MouseDoubleClick" Handler="DataGridAppLogCell_MouseDoubleClick"/>
    </Style>
</DataGrid.Resources>

C#:
//while是個令人擔心會吃效能的地方,測試耗時約1~2毫秒
//觀察Cell和Row差了6層,順序如下:
//0:System.Windows.Controls.DataGridCell
//1:System.Windows.Controls.DataGridCellsPanel
//2:System.Windows.Controls.ItemsPresenter
//3:System.Windows.Controls.Primitives.DataGridCellsPresenter
//4:System.Windows.Controls.Primitives.SelectiveScrollingGrid
//5:System.Windows.Controls.Border
//6:System.Windows.Controls.DataGridRow

//在DataGridCell上雙擊
void DataGridAppLogCell_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    AppLog logData = ((DataGridCell)sender).GetItem<AppLog>();
    
    //Do something.
}

//找出DataGridCell所在的DataGridRow
//回傳DataGridRow所代表的資料
static T GetItem<T>(this DataGridCell obj) where T : class
{
    DataGridRow row = obj.FindOwner<DataGridRow>();
    return row == null ? null : (T)row.Item;
}

//找出DataGridRow
static T FindOwner<T>(this DependencyObject obj) where T : DependencyObject
{
    DependencyObject parent = VisualTreeHelper.GetParent(obj);

    while ((parent != null) && !(parent is T))
    {
        parent = VisualTreeHelper.GetParent(parent);
    }

    return parent as T;
}
送禮物贊助創作者 !
0
留言

創作回應

更多創作