2012-02-03 101 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