/ programming

Windows Presentation Foundation

Logical VS Visual Tree

Short and dirty version:
  • The logical tree contains all the elements in their simple, logical relevant, version : A button is simply a button, no matter how fancy his styles.
  • The visual tree contains every single low-level UI element of the button: Border, rectangle, content provider, ...

    It is important to always be mindful of the tree you're currently working in. Sometimes you don't want to work with all the small parts of the button, sometimes you'll want exactly that.
Dependency Properties

In contrast to normal properties these will tell bound entities about updates to their values. You can bind to these and have the UP update automagically when the property changes. There are different types of dependency properties, different ways to set them up and different features they support.

Model View ViewModel

Not directly tied to WPF, but you'll often find it there.
MVVM Schematics

Model

Contains the data. Either the data object itself, or some sort of data access layer.

View

Basically the user interface. Contains all the buttons, lists and panels.

ViewModel

Handles the views logic, obtains the models data and makes it available to the view. Invokes methods of the model class to modify the data. This is the intermediary layer between UI and data.

Binding

Combobox to Enum

Binding to an enum is not all that easy, as WPF can't easily get all the possible values from the enum to list. To work around this a ObjectDataProvider is used, that calls GetValues on the enum we want to list. This Solution is XAML only.

public enum TestEnum
{
    Red,
    Green,
    Yellow
}

In the Window add:

<Window.Resources>
    <ObjectDataProvider x:Key="enumValues" MethodName="GetValues" ObjectType="{x:Type System:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:ExampleEnum"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

And bind like this:

<ComboBox ItemSource="{Binding Source={StaticResource enumValues}}" />

You need to use the xmlns:System="clr-namespace:System;assembly=mscorlib" for the binding to work properly.

DataContext

The DataContext is inherited in C#. So setting it on the MainWindow is sufficient if it should be passed and it should only be done this way. Setting the DataContext multiple times can result in multiple ViewModels which leads to Singletons in the ViewModels to prohibit that behaviour. And Singletons are evil.