<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<Grid Grid.IsSharedSizeScope="True">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="FirstColumn"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ToggleButton Name="m_chkTest"
Grid.Row="0"
Grid.Column="1"
HorizontalAlignment="Left"
Content="Test"
Margin="4"/>
<Grid Grid.Row="1"
Grid.ColumnSpan="2"
Visibility="{Binding IsChecked, ElementName=m_chkTest, Converter={StaticResource ResourceKey=BooleanToVisibilityConverter}}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="FirstColumn"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Test1"/>
<Label Grid.Row="0" Grid.Column="1" Content="Test2"/>
<Label Grid.Row="0" Grid.Column="2" Content="Test3"/>
</Grid>
</Grid>
</Window>
当我切换测试切换按钮时,内容从左到中(由于新的可见内容)。我想要的是默认情况下切换按钮是居中的(因为隐藏的内容,不仅因为我改变它的水平对齐。
此图显示了3种可用状态。我通过单击测试切换按钮实现另一种状态。我不想发生的是第一个。
答案 0 :(得分:2)
您需要一个与BooleanToVisibility不同的转换器,因为该转换器返回Collapsed是为了可见性而不是Hidden,如下所示:
public class BoolHiddenConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is bool && ((bool)value))
return Visibility.Visible;
return Visibility.Hidden;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is Visibility && (Visibility)value == Visibility.Visible)
return true;
return false;
}
}