我必须在WPF应用程序中动态更新字体大小。 在性能方面,哪种方法更好?以下两种方法的优缺点是什么?
我已经在GenericResourceDictionary.xaml中定义了所有使用的FontSizes:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib">
<System:Double x:Key="FontSize_Small">12</System:Double>
<System:Double x:Key="FontSize_Default">14</System:Double>
<System:Double x:Key="FontSize_DefaultPlus">16</System:Double>
<System:Double x:Key="FontSize_HeaderNormal">18</System:Double>
<System:Double x:Key="FontSize_HeaderLarge">20</System:Double>
<System:Double x:Key="FontSize_MenuItem">26</System:Double>
</ResourceDictionary>
用户启动的ViewModel中的运行时FonstSize更改:
方法#1:创建一个新的ResourceDictionary并将其合并。删除旧的字体大小字典(我不删除GenericResourceDictionary.xmal,因为它的样式比字体更多)
private void OnFontSizeChanged_MergeDictionary(string fontSize)
{
string currentDefaultFontSize = Application.Current.Resources["FontSize_Default"]!=null ? Application.Current.Resources["FontSize_Default"].ToString() : null;
//If Current default fontsize is equal to what user is trying to set, then do nothing
if ((currentDefaultFontSize == fontSize) || fontSize.IsNullOrEmpty())
return;
double newDefaultFontSize = Convert.ToDouble(fontSize);
ResourceDictionary rd = new ResourceDictionary();
rd.Add("FontSize_Small", newDefaultFontSize - 2);
rd.Add("FontSize_Default", newDefaultFontSize);
rd.Add("FontSize_DefaultPlus", newDefaultFontSize + 2);
rd.Add("FontSize_HeaderNormal", newDefaultFontSize + 4);
rd.Add("FontSize_HeaderLarge", newDefaultFontSize + 6);
rd.Add("FontSize_MenuItem", newDefaultFontSize + 12);
//Unload old fontSizeResource
Application.Current.Resources.MergedDictionaries.Remove(_fontSizeRD);
//Load new fontSizeResource
Application.Current.Resources.MergedDictionaries.Add(resource);
//assign the new resource to class variable
_fontSizeRD=resource;
}
方法2:GenericResourceDictionary.xaml中的资源密钥已更新
private void OnFontSizeChanged_UpdateResourceKey(string fontSize)
{
string currentDefaultFontSize = Application.Current.Resources["FontSize_Default"]!=null ? Application.Current.Resources["FontSize_Default"].ToString() : null;
//If Current default fontsize is equal to what user is trying to set, then do nothing
if ((currentDefaultFontSize == fontSize) || fontSize.IsNullOrEmpty())
return;
double newDefaultFontSize = Convert.ToDouble(fontSize);
Application.Current.Resources["FontSize_Small"] = newDefaultFontSize - 2;
Application.Current.Resources["FontSize_Default"] = newDefaultFontSize;
Application.Current.Resources["FontSize_DefaultPlus"] = newDefaultFontSize + 2;
Application.Current.Resources["FontSize_HeaderNormal"] = newDefaultFontSize + 4;
Application.Current.Resources["FontSize_HeaderLarge"] = newDefaultFontSize + 6;
Application.Current.Resources["FontSize_MenuItem"] = newDefaultFontSize + 12;
}
谢谢
RDV