2009-09-29 101 views
9

我想知道是否可以添加功能到數據網格左上角的「全選」按鈕,以便它也取消選擇所有行?我有一個附加到按鈕的方法,但是如果我可以從Select All按鈕中觸發這個方法,將功能保留在視圖的相同部分將會很棒。這個「全選」按鈕是否添加了代碼,如果有的話,怎麼會按鈕?我一直無法找到任何示例或建議。WPF Datagrid「全選」按鈕 - 「全部取消選擇」?

回答

11

OK很多搜索後,我發現瞭如何做到讓從科林·埃伯哈特按鈕,在這裏:

Styling hard-to-reach elements in control templates with attached behaviours

然後,我在他的課延長「Grid_Loaded」的方法來添加一個事件處理程序的按鈕,但記得首先刪除默認的「全選」命令(否則,在運行我們添加的事件處理程序後,命令會運行)。

/// <summary> 
/// Handles the DataGrid's Loaded event. 
/// </summary> 
/// <param name="sender">Sender object.</param> 
/// <param name="e">Event args.</param> 
private static void Grid_Loaded(object sender, RoutedEventArgs e) 
{ 
    DataGrid grid = sender as DataGrid; 
    DependencyObject dep = grid; 

    // Navigate down the visual tree to the button 
    while (!(dep is Button)) 
    { 
     dep = VisualTreeHelper.GetChild(dep, 0); 
    } 

    Button button = dep as Button; 

    // apply our new template 
    ControlTemplate template = GetSelectAllButtonTemplate(grid); 
    button.Template = template; 
    button.Command = null; 
    button.Click += new RoutedEventHandler(SelectAllClicked); 
} 

/// <summary> 
/// Handles the DataGrid's select all button's click event. 
/// </summary> 
/// <param name="sender">Sender object.</param> 
/// <param name="e">Event args.</param> 
private static void SelectAllClicked(object sender, RoutedEventArgs e) 
{ 
    Button button = sender as Button; 
    DependencyObject dep = button; 

    // Navigate up the visual tree to the grid 
    while (!(dep is DataGrid)) 
    { 
     dep = VisualTreeHelper.GetParent(dep); 
    } 

    DataGrid grid = dep as DataGrid; 

    if (grid.SelectedItems.Count < grid.Items.Count) 
    { 
     grid.SelectAll(); 
    } 
    else 
    { 
     grid.UnselectAll(); 
    } 

    e.Handled = true; 
} 

本質上,如果任何行未被選中「選擇所有」,如果沒有它的未選中所有'。它的工作原理與你所期望的select/unselect all工作非常相似,我不能相信他們沒有讓默認的命令做到這一點,說實話,也許在下一個版本中。

希望這有助於有人反正 乾杯, 威爾

+0

非常有用的感謝! – Sharun

+2

謝謝 - 如果包含'GetSelectAllButtonTemplate()'的定義,代碼示例將會完整。 – PandaWood

相關問題