【问题标题】:How to set specific ThemeResource for Image control through binding with MVVM?如何通过绑定 MVVM 为 Image 控件设置特定的 ThemeResource?
【发布时间】: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。

【问题讨论】:

  • &lt;Image Source="{Binding ImageToShow}"/&gt;

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


【解决方案1】:

我相信您应该能够使用Application.Current.Resources 对象访问当前所选主题的相关资源...例如:

Image image = (Image)Application.Current.Resources["ShowImage"];

因此,您应该能够从视图模型属性的设置器中返回该值,如下所示:

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 页面。

【讨论】:

  • 嗨,Sheridan,抱歉回复晚了。我将尝试与您一起解决问题并让您知道结果。罗宾。
  • 嗨,谢里登,谢谢。你的回答让我走上了正确的道路。但它确实打破了图像在运行时自动切换到深色或浅色主题。当应用程序下次启动时,它会再次正确应用。因此,我将进一步调查在运行时使用您发送的链接设置正确的主题。谢谢。
  • 嗨@RobinSmits - 你找到任何解决方案了吗?我发现我在同一条船上。我可以以编程方式获取图像,但这会在主题切换时在运行时中断。此外 Application.Current.Resources["ShowImage"] 仅返回深色主题图像,即使您在浅色主题中也是如此。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 2012-02-17
  • 1970-01-01
  • 2015-02-15
  • 2017-12-22
  • 2012-07-19
  • 1970-01-01
相关资源
最近更新 更多