【发布时间】:2015-02-23 00:28:54
【问题描述】:
我是 WPF 新手,在尝试学习它时遇到了 MVVM 框架。现在我正在尝试使用我制作的一个简单的应用程序来实现它,该应用程序可以导入并显示图像。
XAML:
<Window x:Class="mvvmSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Width="1024" Height="768">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<GroupBox Grid.Row="0" Header="Imported Picture">
<Image x:Name="_image" Stretch="Fill"/>
</GroupBox>
<Button Height="50" Grid.Row="1" Content="Import Picture" Click="Button_Click"/>
</Grid>
</Window>
代码背后:
using Microsoft.Win32;
using System;
using System.Windows;
using System.Windows.Media.Imaging;
namespace mvvmSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.DefaultExt = (".png");
open.Filter = "Pictures (*.jpg;*.gif;*.png)|*.jpg;*.gif;*.png";
if (open.ShowDialog() == true)
_image.Source = new BitmapImage(new Uri(open.FileName));
}
}
}
我看了很多关于 mvvm 初学者的教程,阅读了很多关于它的文章,我掌握了它背后的概念。对于我的应用程序,我假设视图与我所拥有的视图相同,但不使用事件,而是对源和按钮使用命令绑定。对于模型,我假设我应该有一个图像属性,但我不确定它是否应该获取并设置文件路径或图像本身。然后,视图模型将包含用于图像检索 (OpenFileDialog) 和按钮命令的函数。我的假设是否正确,或者是否有更好的方法将此应用程序转换为 mvvm。一个示例编码会很棒,所以我可以分析它。
提前致谢,
【问题讨论】:
-
去试试 Caliburn.Micro; ViewModels 作为 View 的资源是一种可怕的模式。我建议您使用 NInject 或 Autofac 或类似方法实现依赖注入。相信我,如果你选择像 Caliburn.Micro 这样的体面的框架,你会更喜欢 MVVM。