Cilvic
Cilvic

Reputation: 3447

How to conditionally hide elements in a TemplateColumn of a WPF DataGrid?

Context: a C# 4.0 WPF application with a datagrid that has one TemplateColumn showing a progress bar.

How can one get the grid to only display the progress bar for certain items based on a condition?

Maybe listening to the events and hiding the cells / setting visibile to false would be an option.

This is how it looks right now (the progress bar is shown for all items):

<UserControl.Resources>
    <DataTemplate x:Key="PotentialDataTemplate">
        <Grid Width="70">
            <ProgressBar
                Height="12"
                VerticalAlignment="Center"
                Value="{Binding Path=Potential, Mode=OneWay}" />
        </Grid>
    </DataTemplate>
</UserControl.Resources>

<DataGrid x:Name="dataGrid"
        ItemsSource="{Binding Path=Items}"
        AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn
            Header="{Binding Source={x:Static text:TextBindingProvider.Instance}, Path=CompendiumHeaderPotential}"
            Width="Auto"
            MinWidth="80"
            CellTemplate="{StaticResource PotentialDataTemplate}"
            IsReadOnly="true"
            SortMemberPath="Potential" />
    </DataGrid.Columns>
</DataGrid>

Upvotes: 2

Views: 3607

Answers (2)

Cilvic
Cilvic

Reputation: 3447

Just found an answer, I simply add the Visibility attribute and Bind it to some conditional Logic in the ViewModel.

    Visibility = "{Binding Path=ShowPotentialBar, Mode=OneWay}

So:

    <Grid Width="70">
        <ProgressBar
            Height="12"
            VerticalAlignment="Center"
            Value="{Binding Path=Potential, Mode=OneWay}" 

            Visibility = "{Binding Path=ShowPotentialBar, Mode=OneWay}" />

    </Grid>

Upvotes: 2

Andrew Hanlon
Andrew Hanlon

Reputation: 7421

You have a couple of options depending on what the conditions are for visibility. If you have a separate property such as "IsPotentialVisible" then you can bind this to the Visibility property of the progressbar using a BooleanToVisibilityConverter.

Next up, if it is a simple condition such as "hide when Potential == 0", then you could create a DataTrigger that handles this condition.

Otherwise you can also create a custom converter that spits out a visibility based on whatever input properties / parameters are required.

Upvotes: 2

Related Questions