WPF: Setting the Width (and Height) as a Percentage Value

前端 未结 7 640
悲&欢浪女
悲&欢浪女 2020-11-27 10:59

Say I want a TextBlock to have its Width equal to it\'s Parent container\'s Width (ie, stretch from side to side) or a percentage of

7条回答
  •  悲哀的现实
    2020-11-27 11:37

    Typically, you'd use a built-in layout control appropriate for your scenario (e.g. use a grid as a parent if you want scaling relative to the parent). If you want to do it with an arbitrary parent element, you can create a ValueConverter do it, but it probably won't be quite as clean as you'd like. However, if you absolutely need it, you could do something like this:

    public class PercentageConverter : IValueConverter
    {
        public object Convert(object value, 
            Type targetType, 
            object parameter, 
            System.Globalization.CultureInfo culture)
        {
            return System.Convert.ToDouble(value) * 
                   System.Convert.ToDouble(parameter);
        }
    
        public object ConvertBack(object value, 
            Type targetType, 
            object parameter, 
            System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    Which can be used like this, to get a child textbox 10% of the width of its parent canvas:

    
        
            
        
        
            
        
    
    

提交回复
热议问题