Search code examples
c#wpfdata-bindingdatagrid

How can I hide a button in "new row" template in WPF Data Grid?


I have a grid having images and buttons to allow the user to add or del the images. Example:

Example

Both button visibility are binded to the model. Xaml:

<DataGridTemplateColumn Header="Photo" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <Button Name="btnAddPhoto" Content=" Add " Visibility="{Binding BtnAddPhotoVisibility}"></Button>
            <Button Name="BtnExcludePhoto" Content=" Del " Visibility="{Binding BtnExcludePhotoVisibility}"></Button>
            <Image  MaxHeight="50" MaxWidth="50" Tag="Photo" Stretch="Uniform" Source="{Binding Photo}" MouseUp="OnMouseUpBinary" />
        </StackPanel>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

And here is model code having the visibility logic for "DEL" button. "ADD" button is similar.

public Visibility BtnExcludePhotoVisibility
{
    get
    {
        if ((this.Photo == null) || (this.Photo.Length == 0))
            return Visibility.Collapsed;
        else
            return Visibility.Visible;
    }
    set { _BtnExcludePhotoVisibility = value; }
}

The problem is: last row (used to add itens) is in the grid but not really binded when open the grid, (like the image). If I click in last row, the class in list is created and the logic that manipulates the control visibility is triggered. After editing the last row, this happens:

enter image description here

The question is: How trigger the visibility logic for DEL button in last row when opening the grid?


Solution

  • Try to set the Fallback property of the binding to Collapsed:

    <Button Name="BtnExcludePhoto" Content=" Del "
        Visibility="{Binding BtnExcludePhotoVisibility, FallbackValue=Collapsed}" />
    

    This should collapse it by default when the binding cannot be resolved.