SizeToContent
ウィンドウのプロパティを使用して、あなたは正しかったと思います!
このコードを試してください (Converter を宣言し、参照を変更してください!):
IValueConverter
子の可視性のためのC#
public sealed class BoolToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool)
{
if ((bool)value)
return Visibility.Visible;
else
return Visibility.Collapsed;
}
else
throw new NotImplementedException();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
ウィンドウの XAML コード
<Window x:Class="TestWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="clr-namespace:TestWpf.Converters"
VerticalAlignment="Stretch"
SizeToContent="WidthAndHeight"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
Title="MainWindow">
<Window.Resources>
<ResourceDictionary>
<converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" />
</ResourceDictionary>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!--Row 1-->
<StackPanel Grid.Row="0"
Orientation="Vertical">
<ToggleButton Content="expand/collapse"
x:Name="Button1" />
<TextBlock FontSize="30"
HorizontalAlignment="Center"
Visibility="{Binding Path=IsChecked, Mode=OneWay, Converter={StaticResource BoolToVisibilityConverter}, ElementName=Button1}"
Text="Sample Text 1" />
</StackPanel>
<!--Row 2-->
<StackPanel Grid.Row="1"
Orientation="Vertical">
<ToggleButton Content="expand/collapse"
x:Name="Button2" />
<TextBlock FontSize="30"
HorizontalAlignment="Center"
Visibility="{Binding Path=IsChecked, Mode=OneWay, Converter={StaticResource BoolToVisibilityConverter}, ElementName=Button2}"
Text="Sample Text 2" />
</StackPanel>
<!--Row 3-->
<StackPanel Grid.Row="2"
Orientation="Vertical">
<ToggleButton Content="expand/collapse"
x:Name="Button3" />
<TextBlock FontSize="30"
HorizontalAlignment="Center"
Visibility="{Binding Path=IsChecked, Mode=OneWay, Converter={StaticResource BoolToVisibilityConverter}, ElementName=Button3}"
Text="Sample Text 3" />
</StackPanel>
</Grid>
</Window>