SlideShare a Scribd company logo
1 of 18
Download to read offline
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

More Related Content

Viewers also liked

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
 

Viewers also liked (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 to Обзор 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 to Обзор 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
 

Recently uploaded

會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 
Neurulation and the formation of the neural tube
Neurulation and the formation of the neural tubeNeurulation and the formation of the neural tube
Neurulation and the formation of the neural tube
SaadHumayun7
 

Recently uploaded (20)

Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
 
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
Exploring Gemini AI and Integration with MuleSoft | MuleSoft Mysore Meetup #45
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resources
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
 
The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. Henry
 
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdf
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdfPost Exam Fun(da) Intra UEM General Quiz - Finals.pdf
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdf
 
MichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdfMichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdf
 
“O BEIJO” EM ARTE .
“O BEIJO” EM ARTE                       .“O BEIJO” EM ARTE                       .
“O BEIJO” EM ARTE .
 
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
 
Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPoint
 
factors influencing drug absorption-final-2.pptx
factors influencing drug absorption-final-2.pptxfactors influencing drug absorption-final-2.pptx
factors influencing drug absorption-final-2.pptx
 
philosophy and it's principles based on the life
philosophy and it's principles based on the lifephilosophy and it's principles based on the life
philosophy and it's principles based on the life
 
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General QuizPragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdfPost Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
 
Neurulation and the formation of the neural tube
Neurulation and the formation of the neural tubeNeurulation and the formation of the neural tube
Neurulation and the formation of the neural tube
 
How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
Word Stress rules esl .pptx
Word Stress rules esl               .pptxWord Stress rules esl               .pptx
Word Stress rules esl .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