问题
in a WPF app, I want to achieve something like this for my groupbox:
The goal is creating a template for the header, just to display something in the left (checkbox + text), and something in the right side (button).
Unfortunately, the only I get is:
what I get http://imageshack.com/a/img513/706/fiaq.png
I would like not to do it programmatically, but everything in the XAML (as cleaner as possible). I mean, using grids, columndefinitions, etc... not dealing with margins that will crash everything when resizing the window.
The XAML I'm using (grid with three columns):
<GroupBox Margin="5">
<GroupBox.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="15"></ColumnDefinition>
<ColumnDefinition Width="100*"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<CheckBox Grid.Column="0"></CheckBox>
<TextBlock Grid.Column="1" Margin="5,0,5,0" Text="This is my groupbox"></TextBlock>
<Button Content="Click" FontSize="8" Background="Yellow" Grid.Column="2" Height="16" Width="54"></Button>
</Grid>
</GroupBox.Header>
</GroupBox>
What do you think?
回答1:
By default header is left align for GroupBox header. But in your case you want few parts to be left aligned and few to be right for which you need to override ControlTemplate
of groupBox header like defined here and here.
However, you can force the Grid to stretch horizontally
so that button can be placed in right. But as you can see in snapshot, border line gets hide for header content so you might get something like this:
Relevant code to achieve this will be:
XAML
<GroupBox Margin="5" x:Name="groupBox"
xmlns:local="clr-namespace:NamespaceOfConverter">
<GroupBox.Resources>
<local:SubtractionConverter x:Key="SubtractionConverter"/>
</GroupBox.Resources>
<GroupBox.Header>
<Grid Width="{Binding ActualWidth, ElementName=groupBox,
Converter={StaticResource SubtractionConverter}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="15"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<CheckBox Grid.Column="0"/>
<TextBlock Grid.Column="1" Margin="5,0,5,0"
Text="This is my groupbox"/>
<Button Content="Click" FontSize="8" Background="Yellow"
HorizontalAlignment="Right" Grid.Column="2"
Height="16" Width="54"/>
</Grid>
</GroupBox.Header>
</GroupBox>
Converter
public class SubtractionConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return (double)value - 25.0;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return Binding.DoNothing;
}
}
来源:https://stackoverflow.com/questions/22981622/wpf-groupbox-header-alignment