通过单击按钮切换网格

本文关键字:网格 按钮 单击 | 更新日期: 2023-09-27 17:50:37

我试图通过点击Button来崩溃Grid。这就是我的Button在xaml:

中的表示方式。
 <Button Grid.Column="1" Grid.RowSpan="3" Width="25" Content="&lt;&lt;" Click="OnClicked" x:Name="btnCollapse"></Button>

我想在单击此Button(类似于停靠的窗口)时折叠Grid,并在再次单击Button时带回Grid。下面的代码是这样做的:

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 ? ">>" : "<<";
}

这工作得很好,我的问题是我怎么能表示这个逻辑纯粹在xaml而不是在后面的代码?

我的布局:

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

通过单击按钮切换网格

您应该将GridVisibility依赖属性绑定到DataContext中的布尔属性(应该实现INotifyPropertyChanged),并使用boolean visibilityconverter:

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;
}
在XAML:

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


如何设置按钮内容:

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}}"/>

风格:

<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>