如何通过绑定MVVM来设置特定的ThemeResource用于图像控制
本文关键字:ThemeResource 用于 图像 控制 绑定 何通过 MVVM 设置 | 更新日期: 2023-09-27 17:49:25
我有一个应用程序,我已经定义了多个themeresource来设置我想使用的多个图像的正确源。我有十几张图片,我可以让应用程序根据需要自动设置浅色或深色主题。
<ResourceDictionary>
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Light">
<Style x:Key="ShowImage" TargetType="Image">
<Setter Property="Source" Value="Assets/image-light.png"/>
</Style>
</ResourceDictionary>
<ResourceDictionary x:Key="Dark">
<Style x:Key="ShowImage" TargetType="Image">
<Setter Property="Source" value="Assets/image-dark.png"/>
</Style>
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
现在,如果我想在XAML中设置一个特定的内联图像,我使用以下代码:
<Grid>
<Image HorizontalAlignment="Center"
VerticalAlignment="Center"
Stretch="None"
Style="{ThemeResource ShowImage}">
</Image>
</Grid>
这适用于我所有的图像,并始终遵循正确的主题。
我正在尝试更改此代码。我必须显示的图像是基于我在MVVM ViewModel中执行的一些逻辑和计算。
在我的ViewModel中,我有一个字符串类型的属性'ImageToShow',它包含了必须显示的图像的themerresource的名称。
我想在ViewModel中使用属性来执行themerresource分配给Image控件。例如下面的…在本例中,ImageToshow属性将包含字符串值ShowImage
。
<Grid>
<Image HorizontalAlignment="Center"
VerticalAlignment="Center"
Stretch="None"
Style="{ThemeResource ImageToShow}">
</Image>
</Grid>
然而,这给了我一个XamlParseException。
是否可以通过MVVM绑定来设置ThemeResource ?或者我应该使用某种转换器来确保字符串的值被用来选择themerresource .
我相信您应该能够使用Application.Current.Resources
对象访问当前选定主题的相关资源…如:
Image image = (Image)Application.Current.Resources["ShowImage"];
因此,你应该能够像这样从视图模型属性的setter返回该值:
public Image ImageToShow
{
get { return (Image)Application.Current.Resources["ShowImage"]; }
}
唯一的问题是,当属性值发生变化时,您需要手动通知INotifyPropertyChanged
接口,以便UI将收到更改通知:
NotifyPropertyChanged("ImageToShow");
您可以在MSCerts网站的用户界面:检测主题模板页面中的更改中找到如何做到这一点的示例。
请参阅如何在MSDN上应用Windows Phone主题资源以获取更多信息。