Search code examples
wpfdatagrid

Hide datagrid cell based on Model property


Having this model:

public class OptimizationSetting
 {
   public bool Selected { get; set; }
   public string SettingName { get; set; }
   public bool HasValue { get; set; }
   public double Value { get; set; }
 }

And this xaml page:

<DataGrid BorderBrush="{x:Null}" ItemsSource="{Binding OptimizationSettings}" Margin="1" IsReadOnly="False" Background="White"
      AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" RowHeaderWidth="20"
      CanUserResizeColumns="False" CanUserResizeRows="False">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Header="Selected" Binding="{Binding Selected}" Width="80"/>
        <DataGridTextColumn Header="Setting" Binding="{Binding SettingName}" Width="*"/>
        <DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="*"/>
    </DataGrid.Columns>
</DataGrid>

I'm trying to hide the DataGrid Value content based on the model HasValue value. Can I achieve this by using styles?


Solution

  • You can find several ways to hide the content of a cell. The following is one example.

    <DataGridTextColumn Header="Value" Binding="{Binding Value}" Width="*">
        <DataGridTextColumn.CellStyle>
            <Style TargetType="{x:Type DataGridCell}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding HasValue, Mode=OneTime}" Value="False">
                        <Setter Property="Visibility" Value="Hidden"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>