我使用本主题中的其他答案来拼凑我的 MVVM 应用程序所需的解决方案。该代码用于翻转工具栏按钮的图像和工具提示(在本例中为隐藏/取消隐藏)。如果我把它们放在一起,它可能会对你有所帮助。
一、xaml文件中按钮的声明:
<Button ToolTip="{Binding ButtonText}">
<Image Height="32" Width="32" Source="{Binding ButtonImage}"/>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:CallMethodAction TargetObject="{Binding}" MethodName="HideAction"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
在我的 ViewModel 类中,我声明:
private BitmapImage _buttonImage;
public BitmapImage ButtonImage
{
get { return _buttonImage; }
set
{
_buttonImage = value;
OnPropertyChanged("ButtonImage");
}
}
private string _buttonText;
public string ButtonText
{
get { return _buttonText; }
set
{
_buttonText = value;
OnPropertyChanged("ButtonText");
}
}
这里是更改按钮的事件处理程序的代码:
public void HideAction()
{
// Hide the thing you want to hide
...
// Flip the button
if (ButtonText == "Hide")
{
ButtonImage = new BitmapImage(new Uri(@"pack://application:,,,/Resources/Unhide32.png", UriKind.RelativeOrAbsolute));
ButtonText = "Unhide";
}
else
{
ButtonImage = new BitmapImage(new Uri(@"pack://application:,,,/Resources/Hide32.png", UriKind.RelativeOrAbsolute));
ButtonText = "Hide";
}
}
在我的 ViewModel 类的构造函数中,我初始化了图像和工具提示:
ButtonImage = new BitmapImage(new Uri(@"pack://application:,,,/Resources/Hide32.png", UriKind.RelativeOrAbsolute));
ButtonText = "Hide";