2012-03-19 77 views
1

我正在使用WPF DataGrid,並且我的模型中綁定了數據的單元格的IsSelected屬性。如果虛擬化在數據網格上關閉,這可以正常工作(VirtualizingStackPanel.IsVirtualizing="False")。DataGrid虛擬化干擾綁定項目選擇

但是,只要我開啓虛擬化,向下滾動,就會發現有些單元格雖然在代碼中被選中,但不再被選中。

我必須使用虛擬化,因爲沒有它,我的datagrid加載方式太慢了。有沒有人有任何建議如何解決這個問題?

更新:

我的代碼(我在代碼綁定背後B/C我不知道我有多少列需要,直到運行時):

for (int i = 0; i < this.CurrentData.Data[0].Length; i++) 
    { 
     TheGrid.Columns.Add(
      new DataGridTextColumn 
      { 
       Header = (this.CurrentData.Rank > 1) ? string.Format(this.culture, headerFormatString, i + 1) : string.Empty, 
       Binding = new Binding(string.Format("[{0}].DataValue", i)) { ValidatesOnDataErrors = true, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }, 
       Width = DataGridLength.Auto, 
       ElementStyle = new Style 
       { 
        TargetType = typeof(TextBlock), 
        Triggers = { this.errorTrigger } 
       }, 

       EditingElementStyle = new Style 
       { 
        TargetType = typeof(TextBox), 
        Triggers = { this.errorTrigger } 
       }, 

       CellStyle = new Style 
       { 
        TargetType = typeof(DataGridCell), 
        Setters = 
        { 
         new Setter 
         { 
          Property = DataGridCell.IsSelectedProperty, 
          Value = new Binding(string.Format("[{0}].IsSelected", i)) { Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }, 
         } 
        }, 
       } 
      }); 
    } 

和我的IsSelected屬性:

private bool isSelected = false; 
    public bool IsSelected 
    { 
     get 
     { 
      return this.isSelected; 
     } 

     set 
     { 
      this.isSelected = value; 
      OnPropertyChanged("IsSelected"); 
     } 
    } 
+0

代碼與您之前陳述的內容相矛盾 – 2012-03-19 18:28:33

+0

虛擬化不應該是一個問題,因爲控件已創建,只有綁定應該被評估。你能給出具體步驟來重現這一點以及你的綁定代碼嗎? – 2012-03-19 18:29:34

+0

oops,複製錯誤的代碼部分。 @ H.B - 也許它「不應該」成爲一個問題......但它是!它可以在關閉虛擬化的情況下工作,並且在打開虛擬時無法使用。 – KrisTrip 2012-03-19 18:31:16

回答

0

當我將VirtualizationMode設置爲Standard時,它似乎解決了這個問題。

信貸轉到@Blam的建議,但因爲他沒有發佈它作爲答案,但我張貼。如果@Blam張貼他的答案而不是評論,我會接受爲正確的,但在此之前,我將其標記爲正確,以幫助未來的用戶。

0

看看你的代碼,似乎單元格級別選擇有一個共享IsSelected屬性和每個單元格w應該嘗試更新此屬性(由於TwoWay綁定),從而影響共享相同源綁定的所有其他單元。

您需要修改此代碼。

你可以發佈IsSelected這個類的代碼嗎?可能是我們可以改變這個數據網格的設置方式。

+0

IsSelected屬性位於綁定數據的每個值上,因此不共享。 – KrisTrip 2012-03-28 14:48:33