数据网格中一列中的WPF样式单元格

时间:2019-01-29 08:36:32

标签: wpf xaml

我有一个问题,我有一个包含4列的表,第4列是一个状态列,我想根据状态为该第4列的单元格上色,所以我尝试了以下方法:

<DataGrid.CellStyle>
  <Style TargetType="{x:Type DataGridCell}">
    <Setter Property="BorderBrush" Value="#bababa" />
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="Foreground" Value="White" />
    <Style.Triggers>
       <DataTrigger Binding="{Binding DataCollectionStatus}" Value="{x:Static collectionStatus:ModuleDataCollectionStatus.Collected}">
           <Setter Property="Background" Value="Green" />
       </DataTrigger>
       <DataTrigger Binding="{Binding DataCollectionStatus}" Value="{x:Static collectionStatus:ModuleDataCollectionStatus.Collecting}">
           <Setter Property="Background" Value="Orange" />
       </DataTrigger>
       <DataTrigger Binding="{Binding DataCollectionStatus}" Value="{x:Static collectionStatus:ModuleDataCollectionStatus.NotCollected}">
           <Setter Property="Background" Value="Red" />
       </DataTrigger>
     </Style.Triggers>
  </Style>
</DataGrid.CellStyle>

<DataGrid.Columns>
  <DataGridTextColumn Width="100" Header="Module type" Binding="{Binding ModuleTypeAsString}" />
  <DataGridTextColumn Width="70" Header="Rack ID" Binding="{Binding RackIdAsString}" />
  <DataGridTextColumn Width="70" Header="Slot no" Binding="{Binding ModuleSlotAsString}" />
  <DataGridTextColumn Width="200" Header="Status" Binding="{Binding DataCollectionStatusAsString}" />
</DataGrid.Columns>

当它根据状态为所有单元格着色时,它会部分起作用,我也尝试将样式添加到DataGridTextColumn,但收到消息,提示我无法访问那些属性。

我只能在第4列做彩色单元格吗?

1 个答案:

答案 0 :(得分:0)

除了在整个数据网格上,还有一个cellstyle属性可在数据网格列上使用。 例如:

    <DataGridTextColumn Binding="{Binding Title}">
         <DataGridTextColumn.CellStyle>
                <Style TargetType="DataGridCell">
                       <Style.Triggers>
                             <Trigger Property="IsSelected" Value="True">
                                    <Setter Property="Background" Value="{Binding bBrush}"/>
                              </Trigger>
                       </Style.Triggers>
                </Style>
         </DataGridTextColumn.CellStyle>
 </DataGridTextColumn>

使用特定于该位置的复杂逻辑,可以更轻松地维护该逻辑以​​将其封装在行视图模型中,并“仅”返回一个画笔进行绑定。 这样,视图就不依赖于枚举或任何枚举。 然后有人认为决定展示是一种观点责任。 我个人的观点是,任何易于维护的都是最好的。

相关问题