【发布时间】:2015-07-29 05:02:01
【问题描述】:
我有一个应用程序,我在其中定义了多个 ThemeResources 来为我想使用的多个图像设置正确的源。我有大约十几个图像,我可以让应用根据需要自动设置浅色或深色主题。
<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”类型的属性,其中包含必须显示的图像的 ThemeResource 的名称。
我想使用 ViewModel 中的属性将 ThemeResource 分配给 Image 控件。因此,例如以下 .. 在这种情况下,属性 ImageToshow 将包含字符串值 ShowImage。
<Grid>
<Image HorizontalAlignment="Center"
VerticalAlignment="Center"
Stretch="None"
Style="{ThemeResource ImageToShow}">
</Image>
</Grid>
然而,这给了我一个 XamlParseException。
是否可以通过 MVVM 绑定来设置 ThemeResource?或者我应该使用某种转换器来确保字符串的值用于选择 ThemeResource。
【问题讨论】:
-
<Image Source="{Binding ImageToShow}"/>
标签: c# xaml mvvm windows-phone-8.1 winrt-xaml