How can I make a WPF combo box have the width of its widest element in XAML?

前端 未结 13 2097
清酒与你
清酒与你 2020-11-30 18:58

I know how to do it in code, but can this be done in XAML ?

Window1.xaml:



        
13条回答
  •  失恋的感觉
    2020-11-30 19:30

    I ended up with a "good enough" solution to this problem being to make the combo box never shrink below the largest size it held, similar to the old WinForms AutoSizeMode=GrowOnly.

    The way I did this was with a custom value converter:

    public class GrowConverter : IValueConverter
    {
        public double Minimum
        {
            get;
            set;
        }
    
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var dvalue = (double)value;
            if (dvalue > Minimum)
                Minimum = dvalue;
            else if (dvalue < Minimum)
                dvalue = Minimum;
            return dvalue;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
    

    Then I configure the combo box in XAML like so:

     
            
                
            
            ...
            
        
    

    Note that with this you need a separate instance of the GrowConverter for each combo box, unless of course you want a set of them to size together, similar to the Grid's SharedSizeScope feature.

提交回复
热议问题