Mike
Mike

Reputation: 3284

Toggle a grid by clicking a button

I'm trying to collapse a Grid by clicking on a Button. This is how my Button is represented in xaml:

 <Button Grid.Column="1" Grid.RowSpan="3" Width="25" Content="&lt;&lt;" Click="OnClicked" x:Name="btnCollapse"></Button>

I want to collapse a Grid on clicking this Button (something like a docked window) and bring back the Grid on clicking on the Button again. This is how I do that in the code behind:

private bool clicked;
private void OnClicked(object sender, RoutedEventArgs e)
{
    clicked             = !clicked;
    //leftPane is my grid
    leftPane.Visibility = clicked ? Visibility.Collapsed:Visibility.Visible;
    btnCollapse.Content = clicked ? ">>" : "<<";
}

This works fine, my question is how can I represent this logic purely in xaml rather than in the code behind?

My layout:

<Grid>
<Grid/>
<GridSplitter/>
</Grid>
<Button/>

Upvotes: 1

Views: 1919

Answers (1)

snurre
snurre

Reputation: 3105

You should bind the Visibility dependency property of your Grid to a boolean property in the DataContext (which should implement INotifyPropertyChanged) and use a BooleanToVisibilityConverter:

private bool _isGridVisible;
public bool IsGridVisible
{
    get { return _isGridVisible; }
    set
    {
        if (_isGridVisible != value)
            return;
        _isGridVisible = value;
        OnPropertyChanged("IsGridVisible"); // This can sometimes be named RaisePropertyChanged
    }
}

private void OnClick(object sender, RoutedEventArgs e)
{
    IsGridVisible = !IsGridVisible;
}

In XAML:

<Grid Visibility="{Binding IsGridVisible, Converter={StaticResource BooleanToVisibilityConverter}">
    <!-- stuff -->
</Grid>


How to set button content:

IValueConverter:

public class MyBooleanToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool)value ? ">>" : "<<";
    }

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

<Button Click="OnClick" Content="{Binding IsGridVisible, Converter={StaticResource MyBooleanToStringConverter}}"/>

Style:

<Button Click="OnClick">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Content" Value="<<"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsGridVisible}" Value="False">
            <Setter Property="Content" Value=">>"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

Upvotes: 4

Related Questions