Обзор C# WPF MVVM

1,325 views

Published on

Обзор C# WPF MVVM для студентов БФУ им. И. Канта в рамках Winter Coding School
06.02.2014

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,325
On SlideShare
0
From Embeds
0
Number of Embeds
219
Actions
Shares
0
Downloads
12
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Обзор C# WPF MVVM

  1. 1. C# WPF MVVM Мария Нащанская ведущий программист Неолант
  2. 2. «Художественная» Литература «Совершенный код» Стив Макконнелл «Deadline. Роман об управлении проектами» Том ДеМарко C# Джеффри Рихтер «CLR via C#» «Программирование на платформе Microsoft.NET Framework 4.5 на языке C#» Эндрю Троелсен «Язык программирования C# 5.0 и платформа .NET 4.5» WPF Адам Натан «WPF 4. Unleashed» (Подробное руководство) Мэтью Макдональд
  3. 3. Другие материалы msdn.microsoft.com Google :)
  4. 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. 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. 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. 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. 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. 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. 10. MVVM msdn о MVVM Pattern: http:/ /bit.ly/1k2Q6sY Events Прямая связь только так: View ViewModel Model Чтобы не было соблазна, создавайте три разных проекта (Project) в одном Solution: ! OurProgram.View OurProgram.ViewModel OurProgram.Model
  11. 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. 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. 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. 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. 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. 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. 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. 18. Спасибо за внимание! Мария Нащанская s.maria.k@gmail.com ! @merry_ejik

×