您可以通过使用 ValueConverter 将 Expander.Header 中的 Grid 的宽度设置为相对于 Expander.ActualWidth 的值来实现所需的结果,如下所示:
<Expander Name="MyExpander" IsExpanded="True" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" Background="Blue">
<Expander.Header>
<Grid HorizontalAlignment="Stretch" Background="BurlyWood" Width="{Binding ElementName=MyExpander, Path=ActualWidth, Converter={MyConverters:ExpanderHeaderWidthConverter}, ConverterParameter=30}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Path=Name, StringFormat=\{0:D\}}" FontWeight="Bold" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Grid.Column="2">
<TextBlock Text="Total : "/>
<TextBlock Text="{Binding Path=Items, Converter={StaticResource sumConverter}}" FontWeight="Bold"/>
</StackPanel>
</Grid>
</Expander.Header>
<ItemsPresenter />
</Expander>
值转换器的代码:
public abstract class BaseConverter : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
public class ExpanderHeaderWidthConverter : BaseConverter, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// The actuacl Width of the Expander
double width = (double)value;
// Default width difference
double diff = 25.0;
if (parameter != null)
{
// If the parameter is not null, try to use it as width difference
Double.TryParse(parameter.ToString(), out diff);
}
// If width - diff is less than 0, return double.NaN instead.
if (width - diff < 0)
{
return double.NaN;
}
// Return the modified width
return width - diff;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
double width = (double)value;
double diff = 25.0;
if (parameter != null)
{
Double.TryParse(parameter.ToString(), out diff);
}
return width + diff;
}
}
尝试更改 ConverterParameter,直到获得所需的结果。