WPF 屏蔽DPI改变对程序的影响的解决方案

Converter: 
[ValueConversion(typeof(object), typeof(object))]
   public class DPIConverter : IValueConverter
   {
       public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
       {
           WindowInteropHelper winHelper = new WindowInteropHelper((MainWindow)App.Current.MainWindow);
           IntPtr mainWindowHandle = winHelper.Handle;
           Graphics currentGraphics = Graphics.FromHwnd(mainWindowHandle);
           double currentDpiX = currentGraphics.DpiX;
           double dpiXRatio = currentDpiX / 96;  
         
            if (targetType == typeof(GridLength))
           {
               double data = double.Parse(parameter.ToString());
 
                GridLength gridLength = new GridLength(data / dpiXRatio, GridUnitType.Pixel);
               return gridLength;
           }
           if (targetType == typeof(Thickness))
           {
               Thickness margin = (Thickness)parameter;
               if (margin != null)
               {
                   margin.Top = margin.Top / dpiXRatio;
                   margin.Left = margin.Left / dpiXRatio;
                   margin.Right = margin.Right / dpiXRatio;
                   margin.Bottom = margin.Bottom / dpiXRatio;
                   return margin;
               }
           }
           if (targetType == typeof(double))
           {
               double fontSize = double.Parse(parameter.ToString());
               return fontSize / dpiXRatio;
           }
           if(targetType==typeof(System.Windows.Point))
           {
               System.Windows.Point point=(System.Windows.Point)parameter;
               point.X=point.X/dpiXRatio;
               point.Y=point.Y/dpiXRatio;
               return point;
           }
           return null;
       }
 
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
       {
           return null;
       }
   }

XMAL Code:
<Image Name="imageIcon" Stretch="Fill" HorizontalAlignment="Left" VerticalAlignment="Top"
                  Width="{Binding Converter={StaticResource DPIConverter},ConverterParameter=32}"
                  Height="{Binding Converter={StaticResource DPIConverter},ConverterParameter=32}">
               <Image.Margin>
                   <Binding Converter="{StaticResource DPIConverter}">
                       <Binding.ConverterParameter>
                           <Thickness Left="18" Top="24" Right="0" Bottom="48"/>
                       </Binding.ConverterParameter>
                   </Binding>
               </Image.Margin>
           </Image>

你可能感兴趣的:(解决方案)