WPF
===
# MVVM
## ViewModel:
* Doesn't need reference to a view.
* The bindings between view and ViewModel are simple to construct, because a ViewModel object is set as the DataContext of a view.
* The bindings between view and ViewModel is reactive.
* Works on Event-EventHandler architecture.
* ViewModels perform any and all mutations on the model data
### DataContext
* Mechanism for allowing elements to inherit info from thier parent elements.
#### DataContext in xaml file
1. Import all the name spaces
* ` xmlns:<namespace>` declares a namespace
```=xml
<!-- MainWindow.xaml -->
<Window
xmlns:views="clr-namespace:<Views Namespace>"
xmlns:viewModels="clr-namespace:<ViewModel Namespace>"
...
...
>
```
2. Define ViewModel Resource and alias it
* `<Element.Resource>` defines resources for the element.
* `x:Key="ViewModelAlias"` defines alias for ViewModel
```=xml
<Element.Resource>
<viewModels:ViewModel x:Key="ViewModelAlias"/>
</Element.Resource>
```
3. Bind ViewModel Resource to the element DataContext
```=xml
<Element.DataContext>
<Binding Source="{ StaticResource ViewModelAlias }"/>
</Element.DataContext>
```
4. Binding Resource attributes to child element
```=xml
<ChildElement Value="{ Binding ViewModelAttribute }">
```
__Note__ Window element is the root element and all subsequent elements would be contained in the `Element` tag.
### `ObservableCollection<T> _V`
* can be used as a XAML object element in WPF.
* Must be a `private readonly` attribute
* Exposed by `public IEnumerable<T> V => _V ` which is exposed to the View Template via the DataContext.
## View
### Templates and Styling
* Global Styles are specified in the `App.xml` file.
```=xml
<!-- App.xml -->
<Application.Resources>
<Style TargetType="<TargetElementName>">
<Setter Property="<PropertyName>" Value="<PropertyName>">
...
<Setter Property="<AnotherPropertyName>" Value="<AnotherPropertyName>">
</Style>
</Application.Resources>
```
* Defining a list view using a ListBox element
```=xml
<!-- ListView.xaml -->
<Element.Resources>
...
<DataTemplate x:Key="<ListItemTemplate>">
<!-- StackPanel is a layout Element -->
<StackPanel>
<TextBlock Text="{ Binding <ItemSourceAttribute> }">
</StackPanel>
</DataTemplate>
</Element.Resources>
...
<!-- ItemSource = ObservableCollection<T> -->
<ListBox ItemsSource="{Binding <ListOfItems>}" ItemTemplate="{StaticResource <ListItemTemplate>}"
```
### Commands
* Basically mutators (actions),
###### tags: c# csharp mvvm wpf