如何通过绑定MVVM为Image控件设置特定的ThemeResource?

时间:2015-05-17 18:27:40

标签: c# xaml mvvm windows-phone-8.1 winrt-xaml

我有一个应用程序,我已经定义了多个ThemeResources来为我想要使用的多个图像设置正确的Source。我有大约12张图片,我可以让应用程序根据需要自动设置Light或Dark主题。

<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中,我有一个类型为string&#39; ImageToShow&#39;的属性。包含必须显示的Image的ThemeResource的名称。

我想使用ViewModel中的属性来执行Image控件的ThemeResource赋值。所以例如以下..在这种情况下,属性ImageToshow将包含字符串值ShowImage

<Grid>        
    <Image HorizontalAlignment="Center" 
       VerticalAlignment="Center" 
       Stretch="None" 
       Style="{ThemeResource ImageToShow}">
    </Image>
</Grid>

然而,这给了我一个XamlParseException。

是否可以通过MVVM绑定设置ThemeResource?或者我应该使用某种转换器来确保使用字符串的值来选择ThemeResource。

1 个答案:

答案 0 :(得分:0)

我相信您应该能够使用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网站的User Interface : Detecting Changes in the Theme Template页面找到如何执行此操作的示例。

有关详细信息,请参阅MSDN上的How to apply theme resources for Windows Phone页面。

相关问题