2012-02-03 102 views
1

我有一個DataGridTemplateColumn,它定義了一個綁定了Background和Foreground屬性的TextBlock。這允許顏色根據綁定屬性的值進行更改。到目前爲止,除了我希望默認選定的行顏色覆蓋我綁定的背景顏色之外,還好。我如何在xaml中做到這一點?如何讓wpf DataGridRow選中顏色覆蓋DataGridCell的綁定背景顏色?

<DataGridTemplateColumn Header="Text"> 
    <DataGridTemplateColumn.CellTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding Path=Text}" 
         Background="{Binding Path=BackgroundColor}" 
         Foreground="{Binding Path=ForegroundColor}"/> 
     </DataTemplate> 
    </DataGridTemplateColumn.CellTemplate> 
</DataGridTemplateColumn> 

最終,似乎我需要確定單元格是否在選定的行中。如果是這樣,請使用默認選定的行背景顏色,否則使用綁定的背景顏色。我不知道如何解決這個問題。任何幫助,將不勝感激。

回答

1

你可以直接綁定Background,而不是分配Style,其上的選擇({Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}})爲false,然後才使用DataTriggerTextBlock不要設置Background的結合。

+0

這是完美的解決方案。謝謝你看到我不能。 – user1186751 2012-02-03 22:27:08

0

這還不是最完美的解決方案,但它是相當簡單的...

添加「CurrentBackgroundColor」屬性到您的項目(需要實現屬性更改),默認設置爲BACKGROUNDCOLOR。這是你將背景綁定到的東西。

添加一個雙向的SelectedItem具有以下邏輯綁定到您的DataGrid的屬性:

public Item SelectedItem 
{ 
    get 
    { 
    return selectedItem; 
    } 
    set 
    { 
    if (selectedItem != value) 
    { 
     if (selectedItem != null) 
     { 
     selectedItem.CurrentBackgroundColor = selectedItem.BackgroundColor; 
     } 

     selectedItem = value; 

     if (selectedItem != null) 
     { 
     selectedItem.CurrentBackgroundColor = null; 
     } 

     RaisePropertyChanged("SelectedItem"); 
    } 
    } 
} 

這樣做是

  • 如果有當前選擇的項目,改變它的背景返回其默認值
  • 將selectedItem更新爲新選擇的項目
  • 通過將CurrentBackgroundColor設置爲null來清除CurrentBackgroundColor。這將允許選擇高亮顯示

如果你是一個更好的解決方案後,我會去了解一下EventTriggers

+0

感謝您的意見。我沿着這條路走下去,但是真的在尋找一種xaml解決方案。 – user1186751 2012-02-03 22:28:10