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?
There is a semantic difference.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With