SlideShare a Scribd company logo
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

Algorithmiin shinjilgee
Algorithmiin shinjilgeeAlgorithmiin shinjilgee
Algorithmiin shinjilgee
Алдарболд Э.
 
Matura2014 liceum plastyczne_koszalin
Matura2014 liceum plastyczne_koszalinMatura2014 liceum plastyczne_koszalin
Matura2014 liceum plastyczne_koszalinplastyk
 
20150522_Woobe_Information Kit_Light
20150522_Woobe_Information Kit_Light20150522_Woobe_Information Kit_Light
20150522_Woobe_Information Kit_LightVincent Lebunetel
 
Dentistry @ Its Finest
Dentistry @ Its FinestDentistry @ Its Finest
Dentistry @ Its Finest
Michael Ayzin
 
For Sidney Bechet
For Sidney BechetFor Sidney Bechet
For Sidney Bechetnaomil16
 
Vinayak company & product introduction
Vinayak company & product introductionVinayak company & product introduction
Vinayak company & product introduction
Kishor S
 
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.
Michael Ayzin
 
IBM company human resource
IBM company human resourceIBM company human resource
IBM company human resource
Алдарболд Э.
 
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 UNIVERSITASIsmaya Indri Astuti
 
Wireless Transmission
Wireless TransmissionWireless Transmission
Wireless Transmission
tushar05
 
Digital image processing
Digital image processingDigital image processing
Digital image processing
tushar05
 

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

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
Gill Cleeren
 
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
Paul Stovell
 
XAML/C# to HTML/JS
XAML/C# to HTML/JSXAML/C# to HTML/JS
XAML/C# to HTML/JS
Michael Haberman
 
Samsung WebCL Prototype API
Samsung WebCL Prototype APISamsung WebCL Prototype API
Samsung WebCL Prototype APIRyo Jin
 
Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
Flavius-Radu Demian
 
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
Murat Yener
 
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
MongoDB
 
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
Florina Muntenescu
 
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#
Rainer Stropek
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
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...
Constanța Developers
 
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 NHibernatebwullems
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)
Domenic Denicola
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
Alexander Varwijk
 
Implementing new WebAPIs
Implementing new WebAPIsImplementing new WebAPIs
Implementing new WebAPIs
Julian Viereck
 
MVVM Lights
MVVM LightsMVVM Lights
MVVM Lights
Denis Voituron
 
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 xamarinIbon Landa
 
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)
Vladislav Ermolin
 
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
Denis Voituron
 

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

Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Ashish Kohli
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
NelTorrente
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
MERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDFMERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDF
scholarhattraining
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 

Recently uploaded (20)

Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
Aficamten in HCM (SEQUOIA HCM TRIAL 2024)
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
MERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDFMERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDF
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 

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