1

我试图Grid通过单击 a 来折叠 a Button。这就是我Button在 xaml 中的表示方式:

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

我想Grid在单击此时折叠 a 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/>
4

1 回答 1

4

您应该将您的Visibility依赖属性绑定到(应该实现INotifyPropertyChangedGrid )中的布尔属性并使用BooleanToVisibilityConverterDataContext

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>


如何设置按钮内容:

值转换器:

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>
于 2013-01-04T14:54:19.130 回答