Sei sulla pagina 1di 34

model-view-x

pattern
MODEL-VIEW-X
with a limited or no code-behind
data model
along with business and validation logic.
The view model then provides data from the model in a form that the view can easily use
The view model also provides implementations of
commands that a user of the application initiates in the view.
So why MVVM for WPF?
So why MVVM for WPF?
DependencyProperty and DependencyObject
resolved dynamically
If no local value is set, the dependency
property navigates up the logical tree until it finds a value.
a built-in change notification mechanism.
// Dependency Property
// .NET Property wrapper
Attached Properties
<Canvas> <Button Canvas.Top="20" Canvas.Left="20" Content="Click
me!"/> </Canvas>
Notifications for binding to normal
properties
ObservableCollection<T> Class:
(implements

public class Person : INotifyPropertyChanged
{
private string name;
// Declare the event
public event PropertyChangedEventHandler PropertyChanged;

..
public string PersonName
{
get { return name; }
set
{
name = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("PersonName");
}
}

// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
separate
the object that invokes a command from the logic that executes
the command. This allows for multiple and disparate sources to
invoke the same command logic, and it allows the command logic
to be customized for different targets.
indicate whether an action is
available.
ICommand
RelayCommand

<Button Content=BOO" Height="30" Command="{Binding
Path=BOOCommand}"></Button>
How do we do it all?
NO CODE-BEHIND, NO USAGE OF
REFFERENCES OF THE ViewModel
Threading
DONT FREEZE THE UI
belongs to a thread
You can have one thread per Window but in practice, a WPF
application has one single Dispatcher and one thread to handle the
UI (The UI thread/Main Thread).
Dont touch the UI from the wrong thread
The application can only be responsive (the UI working) when the
UI thread is free and running the message loop
Dont block the UI thread
How?
Async Work
Dispatcher.BeginInvoke pass a delegate to the method and WPF
sends a message to the dispatcher and when that message is
picked up, the delegate will be invoked on the UI thread.
ThreadPool
automatically raises an
event on the UI thread
BackgroundWorker BackgroundWorker
DoWorkEventHandler
MVVM in a threading scenario
More advanced topics
Threading
Unit Testing
ToolKits

Potrebbero piacerti anche