简体   繁体   English

WPF DataGrid - 使用 DataTrigger 将样式应用于首先显示的列

[英]WPF DataGrid - Apply style to whichever column is displayed as first with DataTrigger

In a DataGrid , I need to apply a style based on a certain condition implemented in my data context.DataGrid中,我需要根据在我的数据上下文中实现的特定条件应用样式。 But it has to be applied to the cells of the first column only .但它只能应用于第一列的单元格。

Since a user is allowed to reorder columns, I don't know which is the first one in advance.由于允许用户重新排序列,我不知道哪个是第一个提前。 So I tried to implement it at the CellStyle level, with a condition on the DisplayIndex :所以我尝试在CellStyle级别实现它,条件是DisplayIndex

<Condition Binding="{Binding Column.DisplayIndex, RelativeSource={RelativeSource  Mode=FindAncestor, AncestorType={x:Type DataGridCell}}}" Value="0" />

I put it into a MultiDataTrigger with the condition on the data, that is:我将它放入 MultiDataTrigger 中,并带有数据条件,即:

<Condition Binding="{Binding IsInEvidence}" Value="False" />

IsInEvidence is a bool property in my row-level view model. IsInEvidence是我的行级视图 model 中的bool属性。 If I leave this only, it works fine, but it gets applied to all the cells.如果我只留下它,它可以正常工作,但它会应用于所有单元格。

<DataGrid Items={Binding Items}/>
   <DataGrid.CellStyle>
      <Style TargetType="DataGridCell">
         <Style.Triggers>
            <MultiDataTrigger>
               <MultiDataTrigger.Conditions>
                  <Condition Binding="{Binding IsInEvidence}" Value="False" />
                  <Condition Binding="{Binding Column.DisplayIndex, RelativeSource={RelativeSource  Mode=FindAncestor, AncestorType={x:Type DataGridCell}}}" Value="0" />
               </MultiDataTrigger.Conditions>
               <Setter Property="Background" Value="Yellow"/>
            </MultiDataTrigger>
         </Style.Triggers>
      </Style>
   </DataGrid.CellStyle>

   <!-- Column defintions and so on -->

</DataGrid>

Change your Condition binding to use RelativeSource={RelativeSource Self} , then it works.将您的Condition绑定更改为使用RelativeSource={RelativeSource Self} ,然后它就可以工作了。

<Condition Binding="{Binding Column.DisplayIndex, RelativeSource={RelativeSource Self}}" Value="0"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM