WPF: How to specify units in Dialog Units?

后端 未结 5 949
感情败类
感情败类 2020-12-05 10:22

i\'m trying to figure out how to layout a simple dialog in WPF using the proper dialog units (DLUs).


What\'s a dialog unit?

5条回答
  •  余生分开走
    2020-12-05 10:59

    I know this is very old, but I thought I would attempt to do what the OP asked. And as such this is my attempt. BTW, before I continue, I should point out that for some reason, the OPs measurements didn't quite work out when using DLUs, but I think I've come reasonably close. Also please keep in mind I'm still a relative n00b when it comes to this stuff... so if I've done something wrong or blasphemous... apologies.

    Final Result

    First I had to find a way to get the width and height of a given letter of a given font (In my case, Segoe UI at 10px)... which for that I used this SO answer: how-to-calculate-wpf-textblock-width-for-its-known-font-size-and-characters to which I made a static class to hold the resulting doubles:

    public static class Fonts
    {
        public static double HorizontalDluMultiplier;
        public static double VerticalDluMultiplier;
    
        static Fonts()
        {
            var formattedText = new FormattedText(
                "A",
                CultureInfo.CurrentUICulture,
                FlowDirection.LeftToRight,
                new Typeface("Segoe UI"),
                12.0,
                Brushes.Black);
            Fonts.HorizontalDluMultiplier = formattedText.Width / 4;
            Fonts.VerticalDluMultiplier = formattedText.Height / 8;
        }
    }
    

    Once I had the metrics I had to create a WPF converter that takes a given ConverterParameter (In this case a number in DLUs) and spits out a double of pixels. This is the converter I used...

    public class HorizontalDluToPixelConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return (Double.Parse((parameter as string))) * Fonts.HorizontalDluMultiplier;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    I think it goes without saying that I had a seperate Vertical version of the converter.

    Once that was done, I was just a matter of laying out the window in XAML and when it came to setting heights and widths, using the converter. I used a single grid to lay out the entire window. but to set the column widths and row heights I used the converter like so:

    
        
        
    
    
    
        
        etc...
    
    
        
        etc... etc...
    
    

    Hope this helps future people as well (if it is infact helpful heh)

提交回复
热议问题