您应该将您的Visibility
依赖属性绑定到(应该实现INotifyPropertyChangedGrid
)中的布尔属性并使用BooleanToVisibilityConverter:DataContext
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>