单击按钮切换网格

时间:2013-01-04 14:42:26

标签: c# wpf button grid click

我正在尝试通过点击Grid来折叠Button。这就是我的Button在xaml中的表示方式:

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

我希望在点击Grid(类似停靠的窗口)时折叠Button,然后再次点击Grid时返回Button。这就是我在后面的代码中这样做的方式:

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

1 个答案:

答案 0 :(得分:4)

您应该将Visibility的{​​{1}}依赖项属性绑定到Grid中的布尔属性(应该实现INotifyPropertyChanged)并使用BooleanToVisibilityConverter

DataContext

在XAML中:

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


如何设置按钮内容:

的IValueConverter:

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

风格:

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