Search code examples
c#wpfdatagrid

Hide elements in WPF DataGrid


I have DataGrid in WPF, item source is 2D array of integers (DataGrid2D nuget is used to handle it). Now, how can I hide specific elements? For example, if a cell contains 0, display that cell as empty. I couldn't find anything about it; I'm aware of StringFormat, but it's not a string.


Solution

  • One possible solution would be to use DataGridTextColumn to render your data as a string data type. Binding to such a column will allow using a custom value converter to represent the cell contents based on your own logic.

    <Window x:Class="Solution.MainWindow"
            ...
            xmlns:dataGrid2D="http://gu.se/DataGrid2D">
        <Window.Resources>
            <local:CellValueConverter x:Key="cellValueConverter"/>
        </Window.Resources>
        <Grid>
            <DataGrid AutoGenerateColumns="False"
                      dataGrid2D:ItemsSource.Array2D="{Binding Data2D}">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding C0, Converter={StaticResource cellValueConverter}}" Header="Col 1"/>
                    <DataGridTextColumn Binding="{Binding C1}" Header="Col 2" />
                    <DataGridTextColumn Binding="{Binding C2}" Header="Col 3" />
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Window>
    

    Code-behind:

    public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            public int[,] Data2D { get; set; } = new int[,]
                {
                    {0, 3},
                    {2, 7},
                    {5, 6}
                };
        }
    

    Custom value converter CellValueConverter.cs:

    public class CellValueConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (value.ToString() == "0")
                {
                    return string.Empty;
                }
    
                return value;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    

    P.s. I hope I understood it correctly that you're using the NuGet Package to handle binding to 2D arrays.