我正在使用 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/