WPF hide row in datagrid based on condition

Use a CollectionViewSource to link the DataGrid with your business data. The CollectionViewSource fires a filter event for every row. In this event, your code can decide if the row should be displayed.

Add to your XAML:

<Window.Resources>
  <CollectionViewSource x:Key="sampleViewSource" CollectionViewType="ListCollectionView"/>
</Window.Resources>

<DataGrid DataContext="{StaticResource sampleViewSource}" ItemsSource="{Binding}"
            AutoGenerateColumns="False">

Add the following to your code behind file:

stocksViewSource = ((System.Windows.Data.CollectionViewSource)(FindResource("sampleViewSource")));
sampleViewSource.Filter += sampleViewSource_Filter;

Create the filter eventhandler. You can get the row data from e.Item. By setting e.Accepted you can control if the row should be displayed.


If hideRow is not a field of the table (i.e. not a column in the DataGridRow):

<DataGrid.RowStyle>
    <Style TargetType="{x:Type DataGridRow}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding AnyProp, Converter={StaticResource hiddenConverter}}" Value="True">
                <Setter Property="Visibility" Value="Collapsed"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</DataGrid.RowStyle>

And realize Converter with your logic. The type of the bound variable, AnyProp above, will be yourPropertyType below. AnyProp could be any of the columns in the row.

[ValueConversion(typeof(yourPropType), typeof(bool))]
public class hiddenConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (hideRow == "Yes")
        {
           return true;
        }
        else
        {
           return false;
        }
    }


}

'value' will be AnyProp, and it can be used in the logic that determines whether or not to show the row, or that decision can be based on something else entirely, such as 'hideRow' in the example.


You can do this in Datagrid.ItemContainerStyle instead of doing it in codebehind...

  <DataGrid>
      <DataGrid.ItemContainerStyle>
            <Style TargetType="DataGridRow">
                 <Style.Triggers>
                       <DataTrigger Binding="{Binding PROPERTY}"  Value="VALUE">
                              <Setter Property="Visibility" Value="Collapsed"/>