如何在不同的列表视图中更改gridview资源的背景颜色

时间:2014-03-17 06:02:09

标签: wpf

我有两个ListView使用非共享GridView作为View。我在一个地方指定了GridView。有没有办法在GridView中更改每个ListView的单元格的背景颜色,同时保持其余的东西是常见的?

...
<UserControl.Resources>
    <Style x:Key="myHeaderStyle" TargetType="{x:Type GridViewColumnHeader}">
        <Setter Property="Visibility" Value="Collapsed" />
    </Style>
    <GridView x:Key="gridview" x:Shared="false" ColumnHeaderContainerStyle="{StaticResource myHeaderStyle}">
        <GridView.Columns>
            <GridViewColumn Header="" DisplayMemberBinding="{Binding Size}" />
            <GridViewColumn Header="" DisplayMemberBinding="{Binding Price}" />
        </GridView.Columns>
    </GridView>
</UserControl.Resources>
<DockPanel>
    <TextBlock DockPanel.Dock="Top"  HorizontalAlignment="Stretch" Text="{Binding Symbol}" FontSize="14" TextAlignment="Center"/>
    <StackPanel Orientation="Horizontal">
        <ListView ItemsSource="{Binding Bids}"  View="{DynamicResource gridview}" />
        <ListView ItemsSource="{Binding Offers}" View="{DynamicResource gridview}"/>
    </StackPanel>
</DockPanel>

1 个答案:

答案 0 :(得分:1)

是的,你可以这样做,但为此你需要使用TextBlock定义CellTemplate并在其上设置背景,因为GridViewColumn没有公开background属性。

此外,您可以利用WPF的动态资源和资源查找行为,即在逻辑树中向上搜索资源。因此,将TextBlock的背景绑定到某个资源键,您可以在其资源部分下为不同的ListView单独定义。

<GridView.Columns>
   <GridViewColumn Header="">
      <GridViewColumn.CellTemplate>
         <DataTemplate>
           <TextBlock Text="{Binding Size}"
                      Background="{DynamicResource CellBackgroundColor}"/>
         </DataTemplate>
      </GridViewColumn.CellTemplate>
   </GridViewColumn>
   <GridViewColumn Header="">
      <GridViewColumn.CellTemplate>
         <DataTemplate>
            <TextBlock Text="{Binding Price}"
                       Background="{DynamicResource CellBackgroundColor}"/>
         </DataTemplate>
      </GridViewColumn.CellTemplate>
   </GridViewColumn>
</GridView.Columns>

在ListView下定义资源,如下所示:

<StackPanel Orientation="Horizontal">
  <ListView ItemsSource="{Binding Bids}" View="{DynamicResource gridview}">
     <ListView.Resources>
        <SolidColorBrush x:Key="CellBackgroundColor" Color="Red"/>
     </ListView.Resources>
  </ListView>
  <ListView ItemsSource="{Binding Offers}" View="{DynamicResource gridview}">
     <ListView.Resources>
       <SolidColorBrush x:Key="CellBackgroundColor" Color="Yellow"/>
     </ListView.Resources>
  </ListView>
</StackPanel>