http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial

这篇文章醍醐灌顶,入门良药啊!

Introduction

Assuming that you have a decent understanding of C#, getting started in WPF isn't too difficult. I started looking at WPF a while ago, and didn't find many helpful MVVM tutorials. Hopefully this article addresses that.

As with learning any new technology, you get the benefit of hindsight. From my perspective, almost every tutorial on WPF I've come across is inadequate for one of several reasons:

  • The example is all in XAML.
  • The example glosses over the key facts that would actually make your life easier.
  • The example tries to show off WPF/XAML's capabilities with lots of pointless effects that aren't helping you.
  • The example uses classes that have properties that appear far too similar to framework keywords and classes, and are therefore difficult to identify in the (XAML) code as being user defined (the ListBox GroupStyle's Name attribute is a complete headache for novices).

So to address this, I've written this based on what I would have liked to have found as the #1 hit on Google after typing 'WPF Tutorial'. This article may not be 100% correct, or even do things 'the one true way', but it will illustrate the main points that I wish I had found in one place 6 months ago.

I will quickly introduce some topics, then show an example that explains or demonstrates each point. Accordingly, I haven't really attempted to make the GUIs pretty, that's not the point of this article (see the bullet points above).

As this tutorial is quite long, I've elided quite a lot of code for brevity, so please download the attached zip file, and look at the examples (.NET 4.0/VS2010). Each example builds on the previous one.

The Basics

  1. The most important thing about WPF is data binding. In short, you have some data, typically in a collection of some sort, and you want to display it to the user. You can 'bind' your XAML to the data.
  2. WPF has two parts, the XAML which describes your GUI layout and effects, and the code-behind that is tied to the XAML.
  3. The neatest and probably most reusable way to organise your code is to use the 'MVVM' pattern: Model, View, ViewModel. This has the aim of ensuring that your View contains minimal (or no) code, and should be XAML-only.

The Key Points You Need to Know

  1. The collection you should use to hold your data is the ObservableCollection<>. Not a list, not adictionary, but an ObservableCollection. The word 'Observable' is the clue here: the WPF window needs to be able to 'observe' your data collection. This collection class implements certain interfaces that WPF uses.
  2. Every WPF control (including 'Window's) has a 'DataContext' and Collection controls have an 'ItemsSource' attribute to bind to.
  3. The interface 'INotifyPropertyChanged' will be used extensively to communicate any changes in the data between the GUI and your code.

Example 1: Doing It (mostly) Wrong

The best way to start is an example. We will start with a Song class, rather than the usual Person class. We can arrange songs into Albums, or one large collection, or by Artist. A simple Song class would be as follows:

Hide   Copy Code
public class Song
{#region Membersstring _artistName;string _songTitle;#endregion #region Properties /// The artist name. public string ArtistName { get { return _artistName; } set { _artistName = value; } } /// The song title. public string SongTitle { get { return _songTitle; } set { _songTitle = value; } } #endregion } 

In WPF terminology, this is our 'Model'. The GUI is our 'View'. The magic that data binds them together is our 'ViewModel', which is really just an adapter that turns our Model into something that the WPF framework can use. So just to reiterate, this is our 'Model'.

Since we've created a Song as a reference type, copies are cheap and light on memory. We can create ourSongViewModel quite easily. What we need to consider first is, what are we going to (potentially) display? Suppose we just care about the song's artist name, not the song title, then the SongViewModel could be defined as follows:

Hide   Copy Code
public class SongViewModel
{Song _song;public Song Song{get{return _song;}set { _song = value; } } public string ArtistName { get { return Song.ArtistName; } set { Song.ArtistName = value; } } }

Except that this isn't quite correct. Since we're exposing a property in our ViewModel, we would obviously want a change to the song's artist name made in the code to be automatically shown in the GUI, and vice versa:

Hide   Copy Code
SongViewModel song = ...;
// ... enable the databinding ...
//  change the name
song.ArtistName = "Elvis"; // the gui should change

Notice that in all the examples here, we create our view model *declaratively*, i.e., we do this in the XAML:

Hide   Copy Code
<Window x:Class="Example1.MainWindow"xmlns:local="clr-namespace:Example1"> <Window.DataContext> <!-- Declaratively create an instance of our SongViewModel --> <local:SongViewModel /> </Window.DataContext>

This is equivalent to doing this in your code-behind MainWindow.cs:

Hide   Copy Code
public partial class MainWindow : Window
{SongViewModel _viewModel = new SongViewModel();public MainWindow(){InitializeComponent();base.DataContext = _viewModel; } } 

And removing your DataContext element in the XAML:

Hide   Copy Code
<Window x:Class="Example1.MainWindow"xmlns:local="clr-namespace:Example1"> <!-- no data context -->

This is our view:

Clicking the button does not update anything, because we have not completely implemented data binding.

Data Binding

Remember I said at the start that I would choose a property that stands out. In this example, we want to display the ArtistName. I chose this name because it is NOT the same as any WPF attribute. There are a countless number of examples on the web that choose a Person class and then a Name attribute (the Name attribute exists on multiple .NET WPF classes). Perhaps the authors of the articles just don't realise that this is particularly confusing for beginners (who are, curiously enough, the target audience of these articles).

There are dozens of other articles about data binding out there, so I won't cover it here. I hope the example is so trivial that you can see what is going on.

To bind to the ArtistName property on our SongViewModel, we simply do this in the MainWindow.xaml:

Hide   Copy Code
<Label Content="{Binding ArtistName}" /> 

The 'Binding' keyword binds the content of the control, in this case a Label, to the property 'ArtistName' of the object returned by DataContext. As you saw above, we set our DataContext to an instance ofSongViewModel, therefore we are effectively displaying _songViewModel.ArtistName in the Label.

Once again: clicking the button does not update anything, because we have not completely implemented data binding. The GUI is not receiving any notifications that the property has changed.

Example 2: INotifyPropertyChanged

This is where we have to implement the cunningly named interface: INotifyPropertyChanged. As it says, any class that implements this interface, notifies any listeners when a property has changed. So we need to modify our SongViewModel class a little bit more:

Hide   Shrink    Copy Code
public class SongViewModel : INotifyPropertyChanged{#region Construction/// Constructs the default instance of a SongViewModelpublic SongViewModel() { _song = new Song { ArtistName = "Unknown", SongTitle = "Unknown" }; } #endregion #region Members Song _song; #endregion #region Properties public Song Song { get { return _song; } set { _song = value; } } public string ArtistName { get { return Song.ArtistName; } set { if (Song.ArtistName != value) { Song.ArtistName = value; RaisePropertyChanged("ArtistName"); } } } #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion #region Methods private void RaisePropertyChanged(string propertyName) { // take a copy to prevent thread issues PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion }

There are several things now happening here. Firstly, we check to see if we are going to really change the property: this improves performance slightly for more complex objects. Secondly, if the value has changed, we raise the PropertyChanged event to any listeners.

So now we have a Model, and a ViewModel. We just need to define our View. This is just our MainWindow:

Hide   Copy Code
<Window x:Class="Example2.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Example2" Title="Example 2" SizeToContent="WidthAndHeight" ResizeMode="NoResize" Height="350" Width="525"> <Window.DataContext> <!-- Declaratively create an instance of our SongViewModel --> <local:SongViewModel /> </Window.DataContext> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Label Grid.Column="0" Grid.Row="0" Content="Example 2 - this works!" /> <Label Grid.Column="0" Grid.Row="1" Content="Artist: " /> <Label Grid.Column="1" Grid.Row="1" Content="{Binding ArtistName}" /> <Button Grid.Column="1" Grid.Row="2" Name="ButtonUpdateArtist" Content="Update Artist Name" Click="ButtonUpdateArtist_Click" /> </Grid> </Window>

To test the databinding, we can take the traditional approach and create a button and wire to its OnClick event, so the XAML above has a button, and Click event, giving the code behind:

Hide   Copy Code
public partial class MainWindow : Window
{#region MembersSongViewModel _viewModel;int _count = 0; #endregion public MainWindow() { InitializeComponent(); // We have declared the view model instance declaratively in the xaml. // Get the reference to it here, so we can use it in the button click event. _viewModel = (SongViewModel)base.DataContext; } private void ButtonUpdateArtist_Click(object sender, RoutedEventArgs e) { ++_count; _viewModel.ArtistName = string.Format("Elvis ({0})", _count); } } 

This is ok, but it is not how we should use WPF: firstly, we have added our 'update artist' logic into our code-behind. It does not belong there. The Window class is concerned with windowing. The second problem is, suppose we want to move logic in the *button* click event to a different control, for example, making it a menu entry. It means we will be cut'n'pasting, and editing in multiple places.

Here is our improved view, where clicking now works:

Example 3: Commands

Binding to GUI events is problematic. WPF offers you a better way. This is ICommand. Many controls have aCommand attribute. These obey binding in the same way as Content and ItemsSource, except you need to bind it to a *property* that returns an ICommand. For the trivial example that we are looking at here, we just implement a trivial class called 'RelayCommand' that implements ICommand.

ICommand requires the user to define two methods: bool CanExecute, and void Execute. The CanExecutemethod really just says to the user, can I execute this command? This is useful for controlling the context in which you can perform GUI actions. In our example, we don't care, so we return true, meaning that the framework can always call our 'Execute' method. It could be that you have a situation where you have a command bound to button, and it can only execute if you have selected an item in a list. You would implement that logic in the 'CanExecute' method.

Since we want to reuse the ICommand code, we use the RelayCommand class that contains all the repeatable code we do not want to keep writing.

To show how easy it is to reuse the ICommand, we bind the Update Artist command to both a button and a menu item. Notice that we no longer bind to Button specific Click event, or Menu specific Click event.

Example 4: Frameworks

By now, if you have read closely, you'll probably notice that a lot of this is just repetitive code: raising INPC, or creating commands. This is mostly boilerplate, and for INPC, we can move it to base class that we call 'ObservableObject'. For the RelayCommand class, we just move that into our .NET class library. This is how all of the MVVM frameworks you find on the web begin (Prism, Caliburn, etc.).

As far as the ObservableObject and RelayCommand classes are concerned, they are rather basic and are the inevitable result of refactoring. Unsurprisingly, these classes are practically the same as those by Josh Smith.

So we move these classes into a small class library that we can reuse in future.

The view looks much the same as before:

Example 5: Collections of Songs, Doing It Wrong

As I said before, in order to display collections of items in your View (i.e. the XAML), you need to use anObservableCollection. In this example, we create an AlbumViewModel, which nicely collects our songs together in something that people understand. We also introduce a simple song database, purely so we can quickly produce some song information for this example.

Your first attempt might be as follows:

Hide   Copy Code
class AlbumViewModel
{#region MembersObservableCollection<Song> _songs = new ObservableCollection<Song>();#endregion
}

You might think: "I have a different view model this time, I want to display the songs as an AlbumViewModel, not a SongViewModel".

We also create some more ICommands and attach them to some buttons:

Hide   Copy Code
public ICommand AddAlbumArtist {}public ICommand UpdateAlbumArtists {}

In this example, clicking 'Add Artist' works fine. But clicking 'Update Artist Names', fails. If you read the yellow highlighted note on this page on MSDN, it explains why:

To fully support transferring data values from binding source objects to binding targets, each object in your collection that supports bindable properties must implement an appropriate property changed notification mechanism such as the INotifyPropertyChanged interface.

Our view looks like this:

Example 6: Collections of Songs, the Right Way

In this final example, we fix the AlbumViewModel to have an ObservableCollection of SongViewModelsthat we created earlier:

Hide   Copy Code
class AlbumViewModel
{#region MembersObservableCollection<SongViewModel> _songs = new ObservableCollection<SongViewModel>();#endregion// code elided for brevity }

Now all our buttons that are bound to commands operate on our collection. Our code-behind inMainWindow.cs is still completely empty.

Our view looks like this:

Conclusion

Instantiating Your ViewModel

One last point that is worth mentioning is that when you declare your ViewModel declaratively in the XAML, you cannot pass it any parameters: in other words, your ViewModel must have an implicit, or explicit default constructor. How you add state to your ViewModel is up to you. You may find it easier to declare theViewModel in the MainWindow.cs code-behind, where you can pass in construction parameters.

Other Frameworks

There are lots of other MVVM Frameworks of wildly different complexity and functionality, targeting WPF, WP7, Silverlight, and any combination of the three.

Finally...

Hopefully these six examples show you how easy it is to write a WPF application using MVVM. I've tried to cover all of the points that I think are important and often discussed in multiple articles.

If you find this article helpful, please feel to vote it up.

If you find faults in this article, or I've said anything wrong, or you have some other issue with it, please leave a comment below explaining why, and how you would fix it.

转载于:https://www.cnblogs.com/smartsensor/p/5066471.html

WPF/MVVM 快速开发相关推荐

  1. WPF快速入门系列(8)——MVVM快速入门

    一.引言 在前面介绍了WPF一些核心的内容,其中包括WPF布局.依赖属性.路由事件.绑定.命令.资源样式和模板.然而,在WPF还衍生出了一种很好的编程框架,即WVVM,在Web端开发有MVC,在WPF ...

  2. 使用Prism提供的类实现WPF MVVM点餐Demo

    由于公司开发的技术需求,近期在学习MVVM模式开发WPF应用程序.进过一段时间的学习,感受到:学习MVVM模式,最好的方法就是用MVVM做几个Demo,因为编程里面的东西还是原来的WPF的相关知识.最 ...

  3. WPF自学入门(十一)WPF MVVM模式Command命令 WPF自学入门(十)WPF MVVM简单介绍...

    WPF自学入门(十一)WPF MVVM模式Command命令 在WPF自学入门(十)WPF MVVM简单介绍中的示例似乎运行起来没有什么问题,也可以进行更新.但是这并不是我们使用MVVM的正确方式.正 ...

  4. Spring Boot快速开发企业级Admin管理后台

    点击上方 好好学java ,选择 星标 公众号重磅资讯,干货,第一时间送达今日推荐:分享一套基于SpringBoot和Vue的企业级中后台开源项目,这个项目有点哇塞!个人原创100W +访问量博客:点 ...

  5. WPF MVVM实例三

    在没给大家讲解wpf mwm示例之前先给大家简单说下MVVM理论知识: WPF技术的主要特点是数据驱动UI,所以在使用WPF技术开发的过程中是以数据为核心的,WPF提供了数据绑定机制,当数据发生变化时 ...

  6. C# WPF MVVM模式Prism框架下事件发布与订阅

    01 - 前言 处理同模块不同窗体之间的通信和不同模块之间不同窗体的通信,Prism提供了一种事件机制,可以在应用程序中低耦合的模块之间进行通信,该机制基于事件聚合器服务,允许发布者和订阅者之间通过事 ...

  7. C# WPF MVVM模式Prism框架从零搭建(经典)

    01 - 前言 目前最新的PRISM的版本是8.1.97,本节以6.3.0.0 讲解,可以在Github上获取PRISM的源码. Prism Github地址:https://github.com/P ...

  8. C# WPF MVVM项目实战(进阶②)

    这篇文章还是在之前用Caliburn.Micro搭建好的框架上继续做的开发,今天主要是增加了一个用户窗体ImageProcessView,然后通过Treeview切换选择项之后在界面显示不同效果的图片 ...

  9. .NET Core:新的快速开发平台

    .NET Core 今年已经发布了 2.0 版本了.技术雷达最近将 .NET Core 从"评估"移到了"试用"阶段,意味着运用这项技术的风险在不断减小.本文将 ...

最新文章

  1. 我与Linux的相识之旅
  2. 机器学习第2天:简单线性回归模型
  3. C# 模拟鼠标移动与点击
  4. C语言内存/指针相关
  5. 68. 文本左右对齐
  6. iOS中的异步和多线程概况
  7. 最大子序列求和_连续子序列最大和与乘积问题的分析
  8. 扩展Kubernetes API
  9. visual C++ 项目和解决方案的区别
  10. 一文弄懂特征缩放(归一化/正则化)
  11. C2597 LNK2001 C++静态成员函数、变量理解
  12. keil软件安装与破解
  13. java实现关注微信公众号推送模板消息
  14. 基于SSM的商城管理系统
  15. CprimePlus 函数2
  16. Android中action启动方法大全
  17. 哪些因素影响苏州企业注册商标?
  18. 一、Oracle数据库
  19. UGUI sprite editor九宫切图用法
  20. 三种方法求最大公约数和最小公倍数

热门文章

  1. 安装jenkins时出现 No such plugin: cloudbees-folder的解决办法
  2. 代码的坏味道之一——译自《重构》
  3. linux 下 oracle 10.2.0.1 32bit netca报错
  4. Linux下添加普通帐号
  5. 小女生的Linux技术~~~Linux常识~~21-30
  6. ecshop模板支持php,[老杨原创]关于ECSHOP模板架设的服务器php版本过高报错的解决方法集合...
  7. JS的常用正则表达式 验证密码
  8. [USACO13JAN] Cow Lineup (单调队列,尺取法)
  9. 03:数据结构 栈、队列、链表与数组
  10. linux lsof/netstat查看进程和端口号相关命令: