| Subject: MVVM-implementation |
| Group: microsoft.public.windows.developer.winfx.avalon |
| Date: 5/6/2008 6:53:01 AM |
| From: =?Utf-8?B?TWF4aW1pbGlhbg==?= [Email Address Protection] |
I have tried following John Gossman's ContactDatabase-example to make a simple application to divide a two decimals, just to grasp the concept of the MVVM-design-pattern. I would like some feeback on it ... First I have a supersimple Model like this: public class Model { public decimal A; public decimal B; } My ViewModel is a bit more complicated: public class ViewModel : INotifyPropertyChanged { Model model; decimal result; ICommand divide; public ViewModel(Model model) { this.model = model; } public decimal A { get { return model.A; } set { model.A = value; OnPropertyChanged("A"); } } public decimal B { get { return model.B; } set { model.B = value; OnPropertyChanged("B"); } } public decimal Result { get { return result; } internal set { result = value; OnPropertyChanged("Result"); } } public ICommand Divide { get { if (divide == null) divide = new DivideCommand(this); return divide; } } public event PropertyChangedEventHandler PropertyChanged; void OnPropertyChanged(string propertyName) { ... } } public class DivideCommand : ICommand { ViewModel viewModel; public DivideCommand(ViewModel viewModel) { this.viewModel = viewModel; this.viewModel.PropertyChanged += new PropertyChangedEventHandler(viewModel_PropertyChanged); } void viewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "B") OnCanExecuteChanged(); } public bool CanExecute(object parameter) { return viewModel.B != 0; } public event EventHandler CanExecuteChanged; void OnCanExecuteChanged() { ... } public void Execute(object parameter) { viewModel.Result = viewModel.A / viewModel.B; } } And lastly I have my View: <Grid x:Name="View" DataContext="..."> // Im setting the DC to a new ViewModel in App.xaml.cs <Button Command="{Binding Path=Divide}">Divide</Button> <TextBox Text="{Binding Path=Result, Mode=OneWay}" /> <Slider Value="{Binding Path=A}" /> <Slider Value="{Binding Path=B}" /> <Label Content="{Binding Path=A, Mode=OneWay}" /> <Label Content="{Binding Path=B, Mode=OneWay}" /> </Grid> How does this look? Should I have the method to Divide in the model or in the viewmodel? Any other comments... ? Thanks in advance! /Maximilian |
| Back |