如何使用MVVM在按钮控件的不同事件上加载不同的图像?

时间:2016-05-25 12:54:56

标签: wpf mvvm

使用MVVM架构,我想在按钮上加载图像。 因为我在很多地方都有类似的按钮,所以我想让它变得很普通。

1)最初在启动表单时,应加载图像。

2)当" MouseEnter"事件然后光标图像应该变为手。

3)当" MouseLeave"事件然后光标图像应更改为箭头。

4)当" MouseLeftButtonDown"然后应该加载一个图像。

5)当" MouseLeftButtonUp"然后应该加载一个图像。

像这样,我想在不同的事件上加载不同的图像,并且需要使用此按钮 许多其他对话。如何设计它可以作为所有人的共同资源。

任何人都可以帮我解决这个问题。

我是WPF的新手。请善意回答。

1 个答案:

答案 0 :(得分:1)

您可以使用附加属性。如果您需要不同的事件,则必须添加更多附加属性。

请注意,#2和#3可能只是Cursor =" Hand"在按钮上。 #3没有任何实现 - 当你离开按钮时,光标会自动改变。我把它添加为附加属性只是为了好玩。它完全没用,只是重复Cursor =" Hand"。

通过将它们拖放到Visual Studio中的项目中,将

disk_blue.png,disk_green.png和disk_yellow.png添加到应用程序的根目录。构建操作是"资源"。

这是一个完整的演示应用程序:

XAML:

<head></head>
<body>
  <h1>Page 2</h1>
  <script>
    window.location.href = "page1.html";
  </script>
</body>

CS:

<Window x:Class="WpfApplication56.MainWindow"
        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:local="clr-namespace:WpfApplication56"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:VM InitialImage="disk_blue.png" MouseLeftButtonDownImage="disk_green.png" MouseLeftButtonUpImage="disk_yellow.png" />
    </Window.DataContext>
    <Grid>
        <Button VerticalAlignment="Center" HorizontalAlignment="Center" Padding="20"
                local:MyButton.MouseEnterCursor="Hand"
                local:MyButton.InitialImage="{Binding InitialImage}"
                local:MyButton.MouseLeftButtonDown="{Binding MouseLeftButtonDownImage}"
                local:MyButton.MouseLeftButtonUp="{Binding MouseLeftButtonUpImage}"
        />
    </Grid>
</Window>

截图

初始(鼠标悬停在它上面以显示光标变化但光标不在图像中):

enter image description here

LeftMouseButtonDown:

enter image description here

LeftMouseButtonUp:

enter image description here