SlideShare una empresa de Scribd logo
1 de 18
Descargar para leer sin conexión
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

Más contenido relacionado

Destacado

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
 

Destacado (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
 

Similar a Обзор 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
 

Similar a Обзор 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
 

Último

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
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Último (20)

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
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...
 
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
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
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
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
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
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
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
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 

Обзор 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