2010-05-04 49 views
4

我看到一些選項可用於行選擇,但'沒有選擇'不是其中之一。我已經嘗試通過將SelectedItem設置爲null來處理SelectionChanged事件,但該行似乎仍然處於選中狀態。如何防止WPF Toolkit DataGrid中的行選擇?

如果沒有簡單的支持來防止這種情況發生,那麼將所選行設置爲與未選定行相同是否容易?這樣可以選擇,但用戶沒有可視指示器。

+0

你想讓它只讀? – Archie 2010-05-04 13:06:58

+0

它已經是隻讀的。我能夠通過單元格上的屬性輕鬆完成此操作。我只是不想讓行選擇。我開始認爲選定的行與未選定的行相同可能是答案。 – Kilhoffer 2010-05-04 13:09:47

回答

5

您必須使用BeginInvoke異步調用DataGrid.UnselectAll才能使其正常工作。我寫了下面的附加屬性來處理這個問題:

using System; 
using System.Windows; 
using System.Windows.Threading; 
using Microsoft.Windows.Controls; 

namespace DataGridNoSelect 
{ 
    public static class DataGridAttach 
    { 
     public static readonly DependencyProperty IsSelectionEnabledProperty = DependencyProperty.RegisterAttached(
      "IsSelectionEnabled", typeof(bool), typeof(DataGridAttach), 
      new FrameworkPropertyMetadata(true, IsSelectionEnabledChanged)); 
     private static void IsSelectionEnabledChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) 
     { 
      var grid = (DataGrid) sender; 
      if ((bool) e.NewValue) 
       grid.SelectionChanged -= GridSelectionChanged; 
      else 
       grid.SelectionChanged += GridSelectionChanged; 
     } 
     static void GridSelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) 
     { 
      var grid = (DataGrid) sender; 
      grid.Dispatcher.BeginInvoke(
       new Action(() => 
       { 
        grid.SelectionChanged -= GridSelectionChanged; 
        grid.UnselectAll(); 
        grid.SelectionChanged += GridSelectionChanged; 
       }), 
       DispatcherPriority.Normal, null); 
     } 
     public static void SetIsSelectionEnabled(DataGrid element, bool value) 
     { 
      element.SetValue(IsSelectionEnabledProperty, value); 
     } 
     public static bool GetIsSelectionEnabled(DataGrid element) 
     { 
      return (bool)element.GetValue(IsSelectionEnabledProperty); 
     } 
    } 
} 

我創造我的解決方案來源this blog post

+0

這是一個很奇怪的問題的解決方案。如果我可以不止一次地讚揚你,我會!完美工作。 – Kilhoffer 2010-05-05 13:21:32

+0

+1,但相當哈克:-) – Karsten 2011-10-27 13:08:23

0

使用屬性'IsHitTestVisible'作爲False可以避免任何行選擇。但它不會允許你使用你的數據網格的滾動條。在這種情況下Datagrid將被鎖定。 另一種解決方案是: 您可以將樣式應用於datagrid的單元格。它爲我工作。請如下使用代碼:
上面的代碼爲我工作。希望它也能爲你工作。

問候, 費沙

1

請申請下方風格datagid細胞來解決這個問題:

<Style x:Key="MyDatagridCellStyle" TargetType="{x:Type Custom:DataGridCell}"> 
     <Setter Property="Focusable" Value="false"/> 
     <Setter Property="Background" Value="Transparent"/> 
     <Setter Property="Foreground" Value="#434342"/> 
     <Setter Property="BorderThickness" Value="0"/> 
     <Setter Property="FontFamily" Value="Arial"/> 
     <Setter Property="FontSize" Value="11"/> 
     <Setter Property="FontWeight" Value="Normal"/> 
</Style> 
相關問題