Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide cell in new row in WPF Datagrid

Tags:

c#

wpf

datagrid

I have a WPF Datagrid that has a template column as defined below:

<DataGridTemplateColumn x:Name="ciDelete" Header="Delete">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button x:Name="btnDelete" HorizontalAlignment="Center" Margin="0" Click="btnDelete_Click" Tag="{Binding Path=ciID}" VerticalAlignment="Center">
                <Image Source="Resources/16x16/delete.png" Stretch="Fill" />
            </Button>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

This displays and works great. However, the button shows in the row for a new item (below). Since this is a delete button, I do not want it to show on the "new item" row.

Button shown in "new row"

I've seen this article on styling the new row, however this seems a bit extreme. I was curious if there was a simpler method for hiding just the button on the "new row" only. Thank you for your help.

like image 213
jmgardn2 Avatar asked Nov 26 '12 19:11

jmgardn2


1 Answers

If it were me, I would write up a quick converter to determine if the datacontext of the DataGridRow is a NewItemPlaceholder:

public class IsNamedObjectVisibilityConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value.GetType().Name == "NamedObject")
        {
            return Visibility.Hidden;
        }
        else
        {
            return Visibility.Visible;
        }

    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

}

And then I would add a RelativeSource binding to the Delete Button Visibility:

<DataGridTemplateColumn x:Name="ciDelete" Header="Delete">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button x:Name="btnDelete" HorizontalAlignment="Center" Margin="0" Click="btnDelete_Click" Tag="{Binding Path=ciID}" VerticalAlignment="Center"
                 Visibility="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGridRow}, Path=DataContext, Converter={StaticResource IsNamedObjectVisibilityConverter}}">
                <Image Source="Resources/16x16/delete.png" Stretch="Fill" />
            </Button>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

That may or may not be the best approach, but it should work.

I hope this helps.

EDIT: I hope that it's obvious, that for the sake of brevity I skipped the part of creating an instance of said converter. This example would assume that you have an instance of the Converter by the exact name of the class. Probably obvious, but worth mentioning. :)

like image 94
XamlZealot Avatar answered Oct 25 '22 04:10

XamlZealot