How can I make a WPF Expander Stretch?

后端 未结 8 808
醉酒成梦
醉酒成梦 2020-12-29 02:34

The Expander control in WPF does not stretch to fill all the available space. Is there any solutions in XAML for this?

8条回答
  •  佛祖请我去吃肉
    2020-12-29 03:28

    The accepted answer draws outside the control because the header content is in one column and the expander button is in the first. Might be good enough for some cases.

    If you want a clean solution you have to change the template of the expander.

    Another way is an attached property:

    using System.Collections.Generic;
    using System.Linq;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    public static class ParentContentPresenter
    {
        public static readonly System.Windows.DependencyProperty HorizontalAlignmentProperty = System.Windows.DependencyProperty.RegisterAttached(
            "HorizontalAlignment",
            typeof(HorizontalAlignment),
            typeof(ParentContentPresenter),
            new PropertyMetadata(default(HorizontalAlignment), OnHorizontalAlignmentChanged));
    
        public static void SetHorizontalAlignment(this UIElement element, HorizontalAlignment value)
        {
            element.SetValue(HorizontalAlignmentProperty, value);
        }
    
        [AttachedPropertyBrowsableForChildren(IncludeDescendants = false)]
        [AttachedPropertyBrowsableForType(typeof(UIElement))]
        public static HorizontalAlignment GetHorizontalAlignment(this UIElement element)
        {
            return (HorizontalAlignment)element.GetValue(HorizontalAlignmentProperty);
        }
    
        private static void OnHorizontalAlignmentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var presenter = d.Parents().OfType().FirstOrDefault();
            if (presenter != null)
            {
                presenter.HorizontalAlignment = (HorizontalAlignment) e.NewValue;
            }
        }
    
        private static IEnumerable Parents(this DependencyObject child)
        {
            var parent = VisualTreeHelper.GetParent(child);
            while (parent != null)
            {
                yield return parent;
                child = parent;
                parent = VisualTreeHelper.GetParent(child);
            }
        }
    }
    

    It lets you do:

    
        
            
                
                
                    ...    
                
            
        
    
    

    Note that the use of the attached property is somewhat fragile as it assumes that there is a ContentPresenter in the template.

提交回复
热议问题