I have a Grid which has several children, one of which is a ScrollViewer. I want the Grid to size itself based on all of its children except the ScrollViewer, which
Pavlo Glazkov's answer works very well for me! I have used it for a control that does not want to specify explicit sizes ... I added some logic and properties to defeat one dimension:
public sealed class NoSizeDecorator
: Decorator
{
///
/// Sets whether the width will be overridden.
///
public static readonly DependencyProperty DisableWidthOverrideProperty
= DependencyProperty.Register(
nameof(NoSizeDecorator.DisableWidthOverride),
typeof(bool),
typeof(NoSizeDecorator),
new FrameworkPropertyMetadata(
false,
FrameworkPropertyMetadataOptions.AffectsMeasure));
///
/// Sets whether the width will be overridden.
///
public bool DisableWidthOverride
{
get => (bool)GetValue(NoSizeDecorator.DisableWidthOverrideProperty);
set => SetValue(NoSizeDecorator.DisableWidthOverrideProperty, value);
}
///
/// Sets whether the height will be overridden.
///
public static readonly DependencyProperty DisableHeightOverrideProperty
= DependencyProperty.Register(
nameof(NoSizeDecorator.DisableHeightOverride),
typeof(bool),
typeof(NoSizeDecorator),
new FrameworkPropertyMetadata(
false,
FrameworkPropertyMetadataOptions.AffectsMeasure));
///
/// Sets whether the height will be overridden.
///
public bool DisableHeightOverride
{
get => (bool)GetValue(NoSizeDecorator.DisableHeightOverrideProperty);
set => SetValue(NoSizeDecorator.DisableHeightOverrideProperty, value);
}
protected override Size MeasureOverride(Size constraint)
{
UIElement child = Child;
if (child == null)
return new Size();
constraint
= new Size(
DisableWidthOverride
? constraint.Width
: 0D,
DisableHeightOverride
? constraint.Height
: 0D);
child.Measure(constraint);
return new Size(
DisableWidthOverride
? child.DesiredSize.Width
: 0D,
DisableHeightOverride
? child.DesiredSize.Height
: 0D);
}
}