我正在对运行时的资源进行一些更改,以便为不同(物理)屏幕尺寸准备应用程序:
var info = DisplayInformation.GetForCurrentView();
Size screenSize = new Size(Math.Round(Window.Current.Bounds.Width * info.RawPixelsPerViewPixel),
Math.Round(Window.Current.Bounds.Height * info.RawPixelsPerViewPixel));
Application.Current.Resources["SmallerText"] = (1.0 / 15.0) * screenSize.Height / info.RawDpiY * 72;
Application.Current.Resources["SmallText"] = (1.0 / 12.0) * screenSize.Height / info.RawDpiY * 72;
Application.Current.Resources["MediumText"] = (1.0 / 10.0) * screenSize.Height / info.RawDpiY * 72;
Application.Current.Resources["LargeText"] = (1.0 / 5.0) * screenSize.Height / info.RawDpiY * 72;
var displayMargin = (1.0 / 320.0) * screenSize.Height;
Application.Current.Resources["DisplayMargin"] = new Thickness(displayMargin);
现在,当我尝试使用修改后的字体大小时,它可以工作:
<Style TargetType="Button" x:Key="BaseButton">
<Setter Property="FontSize" Value="{StaticResource SmallText}" />
但是当我尝试使用修改后的厚度时,应用程序崩溃了:
<Grid Grid.Row="0" Margin="{StaticResource DisplayMargin}">
错误信息非常神秘:
An exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred in MyApp.exe but was not handled in user code
WinRT information: Failed to assign to property '%0'. [Line: 17 Position: 50]
Additional information: The text associated with this error code could not be found.
Failed to assign to property '%0'. [Line: 17 Position: 50]
If there is a handler for this exception, the program may be safely continued.
为什么我不能使用修改后的厚度?如果我不从后面的代码修改它,一切都正常。
修改:变通方法
解决方法#1:
var displayMargin = (1.0 / 320.0) * screenSize.Height;
Application.Current.Resources.Remove("DisplayMargin");
Application.Current.Resources.Add("DisplayMargin", new Thickness(displayMargin));
解决方法#2:
<Grid Grid.Row="0" Margin="{ThemeResource DisplayMargin}">