我想在我的应用程序中覆盖720和1080p的样式。现在我在我的页面.xaml文件中声明资源:
<phone:PhoneApplicationPage.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../Styles/MapViewStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</phone:PhoneApplicationPage.Resources>
我想在页面构造函数中重新定义样式,如下所示:
public MapView()
{
InitializeComponent();
if (ScreenSizeHelper.IsHd)
{
Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/App;component/Styles/MapViewStyles.Hd.xaml", UriKind.Relative)});
}
}
我在调试中检查过,我的字典已添加到MergedDictionaries,但样式没有覆盖。如何刷新MergedDictionaries或重新初始化页面?
答案 0 :(得分:0)
过了一会儿,我想出了一些有趣的解决方案。我创建了一个名为ResourceResolutionManager的特殊类:
public class ResourceResolutionManager
{
public static DependencyProperty ResolutionProperty =
DependencyProperty.RegisterAttached("Resolution", typeof(Resolutions?), typeof(ResourceResolutionManager),
new PropertyMetadata(null, ResolutionChanged));
private static void ResolutionChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != null && (Resolutions)e.NewValue != ScreenExtension.CurrentResolution)
{
var dict = obj as ResourceDictionary;
if (dict != null)
{
dict.Clear();
}
}
}
public static void SetResolution(DependencyObject obj, Resolutions? resolution)
{
obj.SetValue(ResolutionProperty, resolution);
}
public static Resolutions? GetResolution(DependencyObject obj)
{
return (Resolutions?)obj.GetValue(ResolutionProperty);
}
}
我使用助手类确定屏幕分辨率:
public enum Resolutions { Wvga, Wxga, Hd };
public class ScreenExtension
{
public static bool IsWvga
{
get
{
return Application.Current.Host.Content.ScaleFactor == 100;
}
}
public static bool IsWxga
{
get
{
return Application.Current.Host.Content.ScaleFactor == 160;
}
}
public static bool IsHd
{
get
{
return Application.Current.Host.Content.ScaleFactor == 150;
}
}
public static Resolutions CurrentResolution
{
get
{
if (IsWvga) return Resolutions.Wvga;
if (IsWxga) return Resolutions.Wxga;
if (IsHd) return Resolutions.Hd;
throw new InvalidOperationException("Unknown resolution");
}
}
}
我以这种方式在.xaml文件中使用ResourceResolutionManager:
<ResourceDictionary Source="Styles/Common.Hd.xaml">
<core:ResourceResolutionManager.Resolution>
<extensions1:Resolutions>Hd</extensions1:Resolutions>
</core:ResourceResolutionManager.Resolution>
</ResourceDictionary>
在ResourceResolutionManager中,我检查ResourceDictionary中的解析匹配解析,如果不是,我清除ResourceDictionary。