【发布时间】:2011-02-17 20:25:14
【问题描述】:
我正在开发一个 Silverlight 应用程序,并试图坚持使用 MVVM 原则,但是我遇到了一些问题,它根据 ViewModel 中的属性状态更改图像的源。出于所有意图和目的,您可以将我正在实现的功能视为音频应用程序的播放/暂停按钮。当处于“播放”模式时,ViewModel 中的 IsActive 为 true,应显示按钮上的“Pause.png”图像。暂停时,ViewModel 中的 IsActive 为 false,并且按钮上显示“Play.png”。当然,当鼠标悬停在按钮上时,还有两个额外的图像需要处理。
我以为我可以使用Style Trigger,但显然 Silverlight 不支持它们。我一直在查看一个与我的问题类似的论坛帖子,建议使用VisualStateManager。虽然这可能有助于更改悬停/正常状态的图像,但缺少的部分(或者我不理解)是如何通过视图模型设置状态。该帖子似乎仅适用于事件而不是视图模型的属性。话虽如此,我也没有成功完成正常/悬停效果。
下面是我的 Silverlight 4 XAML。还应该注意我正在使用 MVVM Light。
<UserControl x:Class="Foo.Bar.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
mc:Ignorable="d"
d:DesignHeight="100" d:DesignWidth="200">
<UserControl.Resources>
<Style x:Key="MyButtonStyle" TargetType="Button">
<Setter Property="IsEnabled" Value="true"/>
<Setter Property="IsTabStop" Value="true"/>
<Setter Property="Background" Value="#FFA9A9A9"/>
<Setter Property="Foreground" Value="#FF000000"/>
<Setter Property="MinWidth" Value="5"/>
<Setter Property="MinHeight" Value="5"/>
<Setter Property="Margin" Value="0"/>
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Top" />
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Image Source="/Foo.Bar;component/Resources/Icons/Bar/Play.png">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="Active">
<VisualState x:Name="MouseOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Source" Storyboard.TargetName="/Foo.Bar;component/Resources/Icons/Bar/Play_Hover.png" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Image>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Button Style="{StaticResource MyButtonStyle}" Command="{Binding ChangeStatus}" Height="30" Width="30" />
</Grid>
</UserControl>
用视图模型确定的状态更新按钮上的图像的正确方法是什么?
【问题讨论】:
标签: c# mvvm silverlight-4.0