Document directory
Note: This article is reprinted. The original author information and its original link must be reprinted!
Original address: http://www.slfans.com /? Action-viewnews-itemid-16530
Release: | Author: Purple permanent
Recently, mvvm (Model-View_ViewModel) is a great choice for developing WPF/Silverlight. For the purpose of practice, I plan to use Silverlight to make an English-Chinese dictionary (probably because of recent crazy listening to VOA). The following is a simple analysis of this project.
Note: Because Silverlight does not support command, it cannot fully implement the mvvm mode as in WPF.
Old Rules: Check
Let's talk about my development environment.
Windows Server 2008
Visual Studio 2008 with SP1
Sliverlight 2
The following describes how to create an application step by step.
Create a Silverlight project and host it in ASP. net web application (of course, I strongly recommend that the host be in ASP. net MVC, but this project basically has no connection with the host end, and not everyone has installed ASP.. Net MVC, so the host may have a wider audience in the web form that can use the Silverlight control)
In the Silverlight project, create three new folders: model, view, and viewmodel, and add the corresponding files. The final solution view is as follows:
Model/dictmodel. CS and model/sentmodel. CS are pure business models. All attributes must implement the ipropertychanged interface so that the UI can be updated when the value is changed. These two classes inherit propertychangedbase at the same time. This base class is very simple. Please refer to my other article: make the implementation of inotifypropertychanged more elegant.
The code for these two classes is as follows:
Dictmodel. CS
using System;namespace EternalDict.Model{ public class DictModel : PropertyChangedBase { string _key; public string Key { get { return _key; } set { _key = value; this.NotifyPropertyChanged(p => p.Key); } } string _lang; public string Lang { get { return _lang; } set { _lang = value; this.NotifyPropertyChanged(p => p.Lang); } } string _audio; public string Audio { get { return _audio; } set { _audio = value; this.NotifyPropertyChanged(p => p.Audio); } } string _pron; public string Pron { get { return _pron == null ? string.Empty : string.Format("[{0}]", _pron); } set { _pron = value; this.NotifyPropertyChanged(p => p.Pron); } } string _def; public string Def { get { return _def; } set { _def = value; this.NotifyPropertyChanged(p => p.Def); } } System.Collections.ObjectModel.ObservableCollection<SentModel> _sentCollection; public System.Collections.ObjectModel.ObservableCollection<SentModel> SentCollection { get { return _sentCollection; } set { _sentCollection = value; this.NotifyPropertyChanged(p => p.SentCollection); } } }}
Sentmodel. CS
using System;namespace EternalDict.Model{ public class SentModel : PropertyChangedBase { string _orig; public string Orig { get { return _orig; } set { _orig = value; this.NotifyPropertyChanged(p => p.Orig); } } string _trans; public string Trans { get { return _trans; } set { _trans = value; this.NotifyPropertyChanged(p => p.Trans); } } }}
Viewmodel/dictviewmodel. CS is used to provide data for view/dictview. Xmal
Here, I use the API of the Sea word http://dict.cn/ to parse it through LINQ to XML. However, there is a problem. The sea word API can provide the GBK and utf8 encoding services. However, at present, utf8 does not provide Chinese-English Translation, whereas Silverlight does not support GBK encoding conversion, therefore, only English-Chinese search is supported. Maybe one day you will find that Chinese-English search is available, so the API is officially upgraded by haici.
The code for this class is as follows:
Using system; using system. net; using system. XML. LINQ; using system. LINQ; using system. text; using eternaldict. model; namespace eternaldict. viewmodel {public class dictviewmodel {string _ wordtoquery; Public dictmodel DM {get {return _ DM;} set {_ dm = value ;}} private dictmodel _ DM; Public dictviewmodel () {_ dm = new dictmodel ();} public void queryword (string wordtoquery) {This. _ wordtoquery = word Toquery; string apiurlstring = string. Format ("http://api.dict.cn/ws.php? Utf8 = true & Q = {0} ", this. _ wordtoquery); Uri endpoint = new uri (apiurlstring); WebClient client = new WebClient (); client. downloadstringasync (endpoint); client. downloadstringcompleted + = new downloadstringcompletedeventhandler (client_downloadstringcompleted);} void client_downloadstringcompleted (Object sender, downloadstringcompletedeventargs e) {If (E. error = NULL) {This. parsexml (E. result) ;}} v Oid parsexml (string stringtoparse) {/* Silverlight does not support other encoding GBK = encoding. getencoding ("GBK"); encoding utf8 = encoding. utf8; byte [] gbkbytes = GBK. getbytes (stringtoparse); byte [] utf8bytes = encoding. convert (GBK, utf8, gbkbytes); char [] utf8chars = new char [utf8.getcharcount (utf8bytes, 0, utf8bytes. length)]; utf8.getchars (utf8bytes, 0, utf8bytes. length, utf8chars, 0); stringtoparse = new String (utf8chars); */xdocument xdoc = xdocument. parse (stringtoparse); var nodedict = xdoc. root; var audio = nodedict. elements (). where (P => P. name = "audio "). singleordefault (); var lang = nodedict. elements (). where (P => P. name = "Lang "). singleordefault (); var pron = nodedict. elements (). where (P => P. name = "pron "). singleordefault (); var def = nodedict. element ("def "). value; _ DM. audio = audio = N Ull? String. Empty: audio. value; _ DM. Def = def. Equals ("not found ")? "Definition of the word not found": def; _ DM. Key = This. _ wordtoquery; _ DM. lang = NULL? String. Empty: Lang. value; _ DM. pron = NULL? "None": pron. value; var elesents = nodedict. Elements (). Where (P => P. Name = "sent"); If (elesents! = NULL) {_ DM. sentcollection = new system. collections. objectmodel. observablecollection <sentmodel> (); foreach (VAR item in elesents) {sentmodel Sm = new sentmodel (); SM. orig = item. element ("orig "). value; SM. trans = item. element ("trans "). value; _ DM. sentcollection. add (SM );}}}}}
The dictmodel attribute is disclosed to provide data for the view. In the view, the data is fully bound to communicate with it. Now let's take a look at the most important lines of code in dictview. CS.
DictViewModel dvm = new DictViewModel(); public DictView() { InitializeComponent(); Loaded += new RoutedEventHandler(Dict_Loaded); } void Dict_Loaded(object sender, RoutedEventArgs e) { this.DataContext = dvm; }
After the view is loaded, the viewmodel itself is used as its datacontext. When the query button is clicked, The queryword method of dictviewmodel is called.
private void btnLookUp_Click(object sender, RoutedEventArgs e) { dvm.QueryWord(txtWord.Text.Trim()); }
The rest is the UI design in dictview. XAML, and the code will not be pasted. The key is
<StackPanel DataContext="{Binding Dm}" Orientation="Vertical" >
The BM is bound to the datacontext of the stackpanel. All child elements in the visualization tree can be associated with the model through binding.
Source code download: Click here to download