Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the value of creating a viewmodel as DataContext vs as a StaticResource

In this WPF tutorial in level 2, the author creates the viewModel in Window.Resources like so:

<Window.Resource>
    <local:myViewModel x:Key="viewmodel"/>
</Window.Resource>

and binds each value with {Binding myValue, Source={StaticResource myViewModel}}, however other similar tutorials sets Window.DataContext to the viewModel like so:

<Window.DataContext>
    <local:myViewModel />
</Window.DataContext>

then simply binds values using {Binding myValue}.

My question is: Is there an appreciable difference between them, or is this a user preference?

like image 266
Somkun Avatar asked Nov 28 '16 01:11

Somkun


Video Answer


1 Answers

There is a semantic difference.

  • If multiple controls reference the static resource, they all refer to the same object.
  • If you set the DataContext of your UI elements to an instance of your model class, each element gets its own instance.

To illustrate, consider this model class:

public class Model
{
    private static int counter;

    private readonly int id;

    public Model()
    {
        id = counter++;
    }

    public override string ToString()
    {
        return id.ToString();
    }
}

...and some XAML snippets that use it:

<Window.Resources>
    <wpf:Model x:Key="ModelResource"/>
</Window.Resources>
...
<StackPanel HorizontalAlignment="Center" Margin="20" Orientation="Horizontal">
    <Button Content="{StaticResource ModelResource}" />
    <Button Content="{StaticResource ModelResource}" />
    <Button Content="{Binding}">
        <Button.DataContext>
            <wpf:Model />
        </Button.DataContext>
    </Button>
    <Button Content="{Binding}">
        <Button.DataContext>
            <wpf:Model />
        </Button.DataContext>
    </Button>
    <Button Content="{StaticResource ModelResource}" />
</StackPanel>

The output:

enter image description here

like image 132
Petter Hesselberg Avatar answered Sep 18 '22 20:09

Petter Hesselberg