WPF binding Width to Parent.Width*0.3

后端 未结 2 1373
遇见更好的自我
遇见更好的自我 2020-12-30 11:23

I want to bind a control\'s Width to the parent\'s Width, but to a certain scale. Is there a way to do something like this:



        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 11:49

    Sure, but you will need to use a converter. Something like this one:

    using System;
    using System.Globalization;
    using System.Windows.Data;
    using System.Windows.Markup;
    
    namespace WpfTestBench.Converters
    {
        public class PercentageConverter : MarkupExtension, IValueConverter
        {
            private static PercentageConverter _instance;
    
            #region IValueConverter Members
    
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                return System.Convert.ToDouble(value) * System.Convert.ToDouble(parameter);
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
    
            #endregion
    
            public override object ProvideValue(IServiceProvider serviceProvider)
            {
                return _instance ?? (_instance = new PercentageConverter());
            }
        }
    }
    

    And your XAML will look like:

    
        
            
        
    
    

提交回复
热议问题