xaml - View 模型属性更改时如何更改图像源

标签 xaml mvvm windows-phone-8 winrt-xaml

我正在使用 MVVM Light 构建一个 WP8 应用程序,我遇到了一个我找不到且简单的解决方案的愚蠢问题。

在 XAML 页面中,我有以下内容:

        <Button Command="{Binding PlayCommand}" >
            <Image Source="Images/play.png"/>
        </Button>

执行 PlayCommand 时,我将 ViewModel 中 IsPlaying 属性的值更改为 true。
现在,我希望 XAML 页面对 IsPlaying 的更改使用react,并将图像的源更改为“Images/pause.png”。在 WPF 中,我可以使用 DataTriggers 来实现(也不方便),但它似乎在 WP8 中不起作用。当然,我可以像这样将图像源绑定(bind)到 ViewModel,但这超出了 MVVM 的全部目的。
    <Button Command="{Binding PlayCommand}" >
        <Image Source="{Binding PlayButtonImage}"/>
    </Button>

我知道有复杂的解决方案(例如,附加属性、行为等......),但我认为必须有一个简单的解决方案......

最佳答案

也许像这样的转换器类?

public class BoolToIconConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool)
        {
            bool isPlaying = (bool)value;
            if (isPlaying)
                return "Images/pause.png";
            else 
                return "Images/play.png"
        } 
        return "Images/play.png";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

像这样使用
<Button Command="{Binding PlayCommand}" >
    <Image Source="{Binding IsPlaying, Converter={StaticResource BoolToIconConverter}}"/>
</Button>

尽管我认为 MVVM 中的属性不会破坏您的 MVVM 模式,甚至可能比使用值转换器提供更好的性能。

关于xaml - View 模型属性更改时如何更改图像源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20756669/

相关文章:

wpf - XAML:DataTemplate 中的自定义绑定(bind)用于 GridViewColumn CellTemplate

wpf - System.Byte[]' 不是属性 ImageSource 的有效值

c# - 将 View 模型转换为 View

c# - 退出代码 - 2147220978 (0x8004020e)

xaml - Sitecore 自定义对话框应用程序仍为空

.net - WinRT/UWP 帧和页面缓存 : How to create new page instance on Navigate() and keep the page instance on GoBack()

c# - 如何在 UWP 中将 `DependencyProperty` 标记为 `BindsTwoWayByDefault`?

c# - 在 View 中为 MVVM windows 8 动态生成控件

c++ - 压缩库 Windows 运行时

c# - 对 WriteableBitmap 像素的更改不会更新屏幕