SlideShare une entreprise Scribd logo
1  sur  18
Télécharger pour lire hors ligne
C# WPF MVVM

Мария Нащанская
ведущий программист
Неолант
«Художественная»

Литература

«Совершенный код» Стив Макконнелл
«Deadline. Роман об управлении проектами» Том ДеМарко
C#

Джеффри Рихтер «CLR via C#»

«Программирование на платформе Microsoft.NET Framework 4.5 на языке C#»

Эндрю Троелсен «Язык программирования C# 5.0 и платформа .NET 4.5»
WPF

Адам Натан «WPF 4. Unleashed» (Подробное руководство)
Мэтью Макдональд
Другие материалы
msdn.microsoft.com
Google :)
С#
public class Person: BaseClass, IClonable, ICommand
{
private static const cUni = «BFU»;
!

/
/свойство
private string mName;
public string Name
{
get { return mName; }
set { mName = value; }
}

}

/
/свойство
public string Surname { get; set;}
Наследование
!

public abstract class Animal
{
public virtual int LegsCount()
{
return 4;
}

public class Human: Animal
{
public override int LegsCount()
{
return 2;
}

!

!

public override string Say()
{
return «Hello»;
}

public abstract string Say();
}
}

Human john = new Human();
string firstWord = john.Say();
Animal someone = john;
int legsCount = john.LegsCount();
Интерфейсы
public interface ICommand
{
string CommandName
{
get;
}

public class MyCommand: ICommand
{
public string CommandName
{
get { return «MyFirstCommand»; }
}

!

public void Execute()
{
Console.Writeln(«HelloWorld»):
}


void Execute;
}
}

List<ICommand> commands = OurSmartClass.GetCommands();
foreach (var command in commands)
{
command.Execute();
}
События и делегаты
public class SmartClass
{
public delegate void Action (string option);
!

public event Action SomethingHappens;
!

private void SmartOperation()
{
if ( SomethingHappens!=null ) /
/есть ли подписчики
SomethingHappens(«error»);
}

}
SmartClass ourClass = new SmartClass();
ourClass.SomethingHappens += ReactOnEvent;
private void ReactOnEvent (string option) {}
WPF. XAML
CustomerView.xaml

Label

ComboBox

TextBox

Button

code behind
пуст

CustomerView.xaml.cs

Grid

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="6"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="30"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="30"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
</Grid>
CustomerView.xaml
<Grid Margin = "4">
<Grid.ColumnDefinitions … />
<Grid.RowDefinitions … />
<Label Content = "Customer type:" Grid.Row = "0" Grid.Column = "0"
HorizontalAlignment = "Right"/>
<TextBox Text = "{Binding Path = FirstName}" Grid.Row = "2" Grid.Column = "2"/>

<ComboBox ItemsSource = "{Binding Path = CustomerTypeOptions, Mode = OneTime}"
SelectedItem = "{Binding Path = CustomerType}"/>
<Button Content = "Save" Grid.Row = "8" Grid.Column = "2"
HorizontalAlignment = "Right"
Command = "{Binding Path = SaveCommand}"/>
</Grid>
MVVM
msdn о MVVM Pattern:

http:/
/bit.ly/1k2Q6sY

Events

Прямая связь только так:
View

ViewModel

Model

Чтобы не было соблазна,
создавайте три разных
проекта (Project) в одном
Solution:
!
OurProgram.View
OurProgram.ViewModel
OurProgram.Model
Data Binding - привязка данных
public class MainViewModel : BaseViewModel
!
{
private string mFavoriteColor;
!
public string FavoriteColor
{
get { return mFavoriteColor; }
set
{
if (value != mFavoriteColor)
{
mFavoriteColor = value;
OnPropertyChanged("FavoriteColor");
}
}
Чтобы View узнало об
}
изменениях в ViewModel
}
INotifyPropertyChanged
public class BaseViewModel : INotifyPropertyChanged
!
{
#region INotifyPropertyChanged members
!
public event PropertyChangedEventHandler PropertyChanged;
!
protected virtual void OnPropertyChanged (string propertyName)
!
{
!
if (PropertyChanged != null)
!
{
!
var e = new PropertyChangedEventArgs (propertyName);
!
PropertyChanged (this, e);
!
}
!
}
!
#endregion
!
}
App.xaml.cs
DataContext
public partial class App : Application
!
{
protected override void OnStartup(StartupEventArgs e)
{
!
base.OnStartup(e);
!
MainWindow window = new MainWindow();
!
var viewModel = new MainViewModel();
!
window.DataContext = viewModel;
!
window.Show();
!
}
!
}
ICommand
public class MyCommand : ICommand
!
{
#region ICommand members
!
public bool CanExecute (object parameter)
{
… / если команда используется для Button, то при false Button будет не активна
/
!
}
!
public void Execute (object parameter)
!
{
…
!
}
!
public event EventHandler CanExecuteChanged
{
!
add { CommandManager.RequerySuggested += value; }
!
remove { CommandManager.RequerySuggessted -= value; }
!
}
!
#endregion
!
}
Использование RelayCommand
public class CustomerViewModel: BaseViewModel
!
{
private ICommand mSaveCommand;
!
public ICommand SaveCommand
{
get
{
if (mSaveCommand == null)
{
mSaveCommand = new RelayCommand(
param => this.Save(),
param => this.CanSave());
}
return mSaveCommand;
}
}
!
!

}

private void Save() {}
private bool CanSave() {}
Data Validation - IDataErrorInfo
public class CustomerViewModel: BaseViewModel, IDataErrorInfo
!
{
public string IDataErrorInfo.Error
{
get { return (_customer as IDataErrorInfo).Error; }
}

!

!

public string IDataErrorInfo.this[string propertyName]
{
get {
string error = null;
if (propertyName == "CustomerType")
error = this.ValidateCustomerType();
else
error = (_customer as IDataErrorInfo)[propertyName];
CommandManager.InvalidateRequerySuggested();
return error;
}

!

}

}
private string ValidateCustomerType()
{
if (this.CustomerType == Strings.CustomerViewModel_CustomerTypeOption_Company ||
this.CustomerType == Strings.CustomerViewModel_CustomerTypeOption_Person)
return null;
return Strings.CustomerViewModel_Error_MissingCustomerType;
}
IDataErrorInfo, xaml
<Grid>
<Grid.Resources>
<DataTemplate DataType="{x:Type ValidationError}">
<TextBlock FontStyle="Italic" Foreground="Red"
HorizontalAlignment="Right" Margin="0,1"
Text="{Binding Path=ErrorContent}" />
</DataTemplate>
</Grid.Resources>
!

<ComboBox x:Name="customerTypeCmb" Grid.Row="0" Grid.Column="2"
ItemsSource="{Binding Path=CustomerTypeOptions, Mode=OneTime}"
SelectedItem="{Binding Path=CustomerType,
ValidatesOnDataErrors=True}"
Validation.ErrorTemplate="{x:Null}"/>
!

<ContentPresenter Grid.Row="1" Grid.Column="2"
Content="{Binding ElementName=customerTypeCmb,
Path=(Validation.Errors).CurrentItem}"
/>

!
Спасибо за внимание!

Мария Нащанская
s.maria.k@gmail.com
!
@merry_ejik

Contenu connexe

En vedette

Matura2014 liceum plastyczne_koszalin
Matura2014 liceum plastyczne_koszalinMatura2014 liceum plastyczne_koszalin
Matura2014 liceum plastyczne_koszalin
plastyk
 
20150522_Woobe_Information Kit_Light
20150522_Woobe_Information Kit_Light20150522_Woobe_Information Kit_Light
20150522_Woobe_Information Kit_Light
Vincent Lebunetel
 
For Sidney Bechet
For Sidney BechetFor Sidney Bechet
For Sidney Bechet
naomil16
 
PENGARUH KEGIATAN OSPEK TERHADAP ETIKA MAHASISWA BARU MEMASUKI DUNIA UNIVERSITAS
PENGARUH KEGIATAN OSPEK TERHADAP ETIKA MAHASISWA BARU MEMASUKI DUNIA UNIVERSITASPENGARUH KEGIATAN OSPEK TERHADAP ETIKA MAHASISWA BARU MEMASUKI DUNIA UNIVERSITAS
PENGARUH KEGIATAN OSPEK TERHADAP ETIKA MAHASISWA BARU MEMASUKI DUNIA UNIVERSITAS
Ismaya Indri Astuti
 

En vedette (17)

Algorithmiin shinjilgee
Algorithmiin shinjilgeeAlgorithmiin shinjilgee
Algorithmiin shinjilgee
 
Matura2014 liceum plastyczne_koszalin
Matura2014 liceum plastyczne_koszalinMatura2014 liceum plastyczne_koszalin
Matura2014 liceum plastyczne_koszalin
 
Coad slide show
Coad slide showCoad slide show
Coad slide show
 
20150522_Woobe_Information Kit_Light
20150522_Woobe_Information Kit_Light20150522_Woobe_Information Kit_Light
20150522_Woobe_Information Kit_Light
 
Dentistry @ Its Finest
Dentistry @ Its FinestDentistry @ Its Finest
Dentistry @ Its Finest
 
For Sidney Bechet
For Sidney BechetFor Sidney Bechet
For Sidney Bechet
 
Vinayak company & product introduction
Vinayak company & product introductionVinayak company & product introduction
Vinayak company & product introduction
 
Resolution/coda
Resolution/codaResolution/coda
Resolution/coda
 
I&E- Phone
I&E- PhoneI&E- Phone
I&E- Phone
 
COACHING PHILOSOPHY
COACHING PHILOSOPHYCOACHING PHILOSOPHY
COACHING PHILOSOPHY
 
Changing the smile with a dental laser.
 Changing the smile with a dental laser. Changing the smile with a dental laser.
Changing the smile with a dental laser.
 
IBM company human resource
IBM company human resourceIBM company human resource
IBM company human resource
 
Uluru
Uluru   Uluru
Uluru
 
PENGARUH KEGIATAN OSPEK TERHADAP ETIKA MAHASISWA BARU MEMASUKI DUNIA UNIVERSITAS
PENGARUH KEGIATAN OSPEK TERHADAP ETIKA MAHASISWA BARU MEMASUKI DUNIA UNIVERSITASPENGARUH KEGIATAN OSPEK TERHADAP ETIKA MAHASISWA BARU MEMASUKI DUNIA UNIVERSITAS
PENGARUH KEGIATAN OSPEK TERHADAP ETIKA MAHASISWA BARU MEMASUKI DUNIA UNIVERSITAS
 
Foundation 1
Foundation 1Foundation 1
Foundation 1
 
Wireless Transmission
Wireless TransmissionWireless Transmission
Wireless Transmission
 
Digital image processing
Digital image processingDigital image processing
Digital image processing
 

Similaire à Обзор C# WPF MVVM

Samsung WebCL Prototype API
Samsung WebCL Prototype APISamsung WebCL Prototype API
Samsung WebCL Prototype API
Ryo Jin
 
Building an enterprise app in silverlight 4 and NHibernate
Building an enterprise app in silverlight 4 and NHibernateBuilding an enterprise app in silverlight 4 and NHibernate
Building an enterprise app in silverlight 4 and NHibernate
bwullems
 
Cross platform mobile development with visual studio and xamarin
Cross platform mobile development with visual studio and xamarinCross platform mobile development with visual studio and xamarin
Cross platform mobile development with visual studio and xamarin
Ibon Landa
 

Similaire à Обзор C# WPF MVVM (20)

Real world apps with Xamarin and MVVM
Real world apps with Xamarin and MVVMReal world apps with Xamarin and MVVM
Real world apps with Xamarin and MVVM
 
Real-world Model-View-ViewModel for WPF
Real-world Model-View-ViewModel for WPFReal-world Model-View-ViewModel for WPF
Real-world Model-View-ViewModel for WPF
 
XAML/C# to HTML/JS
XAML/C# to HTML/JSXAML/C# to HTML/JS
XAML/C# to HTML/JS
 
Samsung WebCL Prototype API
Samsung WebCL Prototype APISamsung WebCL Prototype API
Samsung WebCL Prototype API
 
Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
Webinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaWebinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and Java
 
MVM - It's all in the (Implementation) Details
MVM - It's all in the (Implementation) DetailsMVM - It's all in the (Implementation) Details
MVM - It's all in the (Implementation) Details
 
P/Invoke - Interoperability of C++ and C#
P/Invoke - Interoperability of C++ and C#P/Invoke - Interoperability of C++ and C#
P/Invoke - Interoperability of C++ and C#
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
 
Building an enterprise app in silverlight 4 and NHibernate
Building an enterprise app in silverlight 4 and NHibernateBuilding an enterprise app in silverlight 4 and NHibernate
Building an enterprise app in silverlight 4 and NHibernate
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Implementing New Web
Implementing New WebImplementing New Web
Implementing New Web
 
Implementing new WebAPIs
Implementing new WebAPIsImplementing new WebAPIs
Implementing new WebAPIs
 
MVVM Lights
MVVM LightsMVVM Lights
MVVM Lights
 
Cross platform mobile development with visual studio and xamarin
Cross platform mobile development with visual studio and xamarinCross platform mobile development with visual studio and xamarin
Cross platform mobile development with visual studio and xamarin
 
Dialogs in Android MVVM (14.11.2019)
Dialogs in Android MVVM (14.11.2019)Dialogs in Android MVVM (14.11.2019)
Dialogs in Android MVVM (14.11.2019)
 
Présentation et bonnes pratiques du pattern MVVM - MIC Belgique
Présentation et bonnes pratiques du pattern MVVM - MIC BelgiquePrésentation et bonnes pratiques du pattern MVVM - MIC Belgique
Présentation et bonnes pratiques du pattern MVVM - MIC Belgique
 

Dernier

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 

Dernier (20)

Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

Обзор C# WPF MVVM

  • 1. C# WPF MVVM Мария Нащанская ведущий программист Неолант
  • 2. «Художественная» Литература «Совершенный код» Стив Макконнелл «Deadline. Роман об управлении проектами» Том ДеМарко C# Джеффри Рихтер «CLR via C#» «Программирование на платформе Microsoft.NET Framework 4.5 на языке C#» Эндрю Троелсен «Язык программирования C# 5.0 и платформа .NET 4.5» WPF Адам Натан «WPF 4. Unleashed» (Подробное руководство) Мэтью Макдональд
  • 4. С# public class Person: BaseClass, IClonable, ICommand { private static const cUni = «BFU»; ! / /свойство private string mName; public string Name { get { return mName; } set { mName = value; } } } / /свойство public string Surname { get; set;}
  • 5. Наследование ! public abstract class Animal { public virtual int LegsCount() { return 4; } public class Human: Animal { public override int LegsCount() { return 2; } ! ! public override string Say() { return «Hello»; } public abstract string Say(); } } Human john = new Human(); string firstWord = john.Say(); Animal someone = john; int legsCount = john.LegsCount();
  • 6. Интерфейсы public interface ICommand { string CommandName { get; } public class MyCommand: ICommand { public string CommandName { get { return «MyFirstCommand»; } } ! public void Execute() { Console.Writeln(«HelloWorld»): }
 void Execute; } } List<ICommand> commands = OurSmartClass.GetCommands(); foreach (var command in commands) { command.Execute(); }
  • 7. События и делегаты public class SmartClass { public delegate void Action (string option); ! public event Action SomethingHappens; ! private void SmartOperation() { if ( SomethingHappens!=null ) / /есть ли подписчики SomethingHappens(«error»); } } SmartClass ourClass = new SmartClass(); ourClass.SomethingHappens += ReactOnEvent; private void ReactOnEvent (string option) {}
  • 8. WPF. XAML CustomerView.xaml Label ComboBox TextBox Button code behind пуст CustomerView.xaml.cs Grid <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="6"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="30"/> <RowDefinition Height="Auto"/> <RowDefinition Height="30"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> </Grid>
  • 9. CustomerView.xaml <Grid Margin = "4"> <Grid.ColumnDefinitions … /> <Grid.RowDefinitions … /> <Label Content = "Customer type:" Grid.Row = "0" Grid.Column = "0" HorizontalAlignment = "Right"/> <TextBox Text = "{Binding Path = FirstName}" Grid.Row = "2" Grid.Column = "2"/> <ComboBox ItemsSource = "{Binding Path = CustomerTypeOptions, Mode = OneTime}" SelectedItem = "{Binding Path = CustomerType}"/> <Button Content = "Save" Grid.Row = "8" Grid.Column = "2" HorizontalAlignment = "Right" Command = "{Binding Path = SaveCommand}"/> </Grid>
  • 10. MVVM msdn о MVVM Pattern: http:/ /bit.ly/1k2Q6sY Events Прямая связь только так: View ViewModel Model Чтобы не было соблазна, создавайте три разных проекта (Project) в одном Solution: ! OurProgram.View OurProgram.ViewModel OurProgram.Model
  • 11. Data Binding - привязка данных public class MainViewModel : BaseViewModel ! { private string mFavoriteColor; ! public string FavoriteColor { get { return mFavoriteColor; } set { if (value != mFavoriteColor) { mFavoriteColor = value; OnPropertyChanged("FavoriteColor"); } } Чтобы View узнало об } изменениях в ViewModel }
  • 12. INotifyPropertyChanged public class BaseViewModel : INotifyPropertyChanged ! { #region INotifyPropertyChanged members ! public event PropertyChangedEventHandler PropertyChanged; ! protected virtual void OnPropertyChanged (string propertyName) ! { ! if (PropertyChanged != null) ! { ! var e = new PropertyChangedEventArgs (propertyName); ! PropertyChanged (this, e); ! } ! } ! #endregion ! }
  • 13. App.xaml.cs DataContext public partial class App : Application ! { protected override void OnStartup(StartupEventArgs e) { ! base.OnStartup(e); ! MainWindow window = new MainWindow(); ! var viewModel = new MainViewModel(); ! window.DataContext = viewModel; ! window.Show(); ! } ! }
  • 14. ICommand public class MyCommand : ICommand ! { #region ICommand members ! public bool CanExecute (object parameter) { … / если команда используется для Button, то при false Button будет не активна / ! } ! public void Execute (object parameter) ! { … ! } ! public event EventHandler CanExecuteChanged { ! add { CommandManager.RequerySuggested += value; } ! remove { CommandManager.RequerySuggessted -= value; } ! } ! #endregion ! }
  • 15. Использование RelayCommand public class CustomerViewModel: BaseViewModel ! { private ICommand mSaveCommand; ! public ICommand SaveCommand { get { if (mSaveCommand == null) { mSaveCommand = new RelayCommand( param => this.Save(), param => this.CanSave()); } return mSaveCommand; } } ! ! } private void Save() {} private bool CanSave() {}
  • 16. Data Validation - IDataErrorInfo public class CustomerViewModel: BaseViewModel, IDataErrorInfo ! { public string IDataErrorInfo.Error { get { return (_customer as IDataErrorInfo).Error; } } ! ! public string IDataErrorInfo.this[string propertyName] { get { string error = null; if (propertyName == "CustomerType") error = this.ValidateCustomerType(); else error = (_customer as IDataErrorInfo)[propertyName]; CommandManager.InvalidateRequerySuggested(); return error; } ! } } private string ValidateCustomerType() { if (this.CustomerType == Strings.CustomerViewModel_CustomerTypeOption_Company || this.CustomerType == Strings.CustomerViewModel_CustomerTypeOption_Person) return null; return Strings.CustomerViewModel_Error_MissingCustomerType; }
  • 17. IDataErrorInfo, xaml <Grid> <Grid.Resources> <DataTemplate DataType="{x:Type ValidationError}"> <TextBlock FontStyle="Italic" Foreground="Red" HorizontalAlignment="Right" Margin="0,1" Text="{Binding Path=ErrorContent}" /> </DataTemplate> </Grid.Resources> ! <ComboBox x:Name="customerTypeCmb" Grid.Row="0" Grid.Column="2" ItemsSource="{Binding Path=CustomerTypeOptions, Mode=OneTime}" SelectedItem="{Binding Path=CustomerType, ValidatesOnDataErrors=True}" Validation.ErrorTemplate="{x:Null}"/> ! <ContentPresenter Grid.Row="1" Grid.Column="2" Content="{Binding ElementName=customerTypeCmb, Path=(Validation.Errors).CurrentItem}" /> !
  • 18. Спасибо за внимание! Мария Нащанская s.maria.k@gmail.com ! @merry_ejik