C# 作为DataContext创建viewmodel与作为StaticResource创建viewmodel的价值是什么

C# 作为DataContext创建viewmodel与作为StaticResource创建viewmodel的价值是什么,c#,wpf,xaml,mvvm,datacontext,C#,Wpf,Xaml,Mvvm,Datacontext,在级别2中,作者在窗口中创建viewModel。参考资料如下: <Window.Resource> <local:myViewModel x:Key="viewmodel"/> </Window.Resource> 然后使用{Binding myValue}简单地绑定值 我的问题是:它们之间是否存在明显的差异,或者这是用户的偏好?存在语义差异 如果多个控件引用静态资源,则它们都引用同一对象 如果将UI元素的DataContext设置为模型类的实例,

在级别2中,作者在
窗口中创建viewModel。参考资料如下:

<Window.Resource>
    <local:myViewModel x:Key="viewmodel"/>
</Window.Resource>
然后使用
{Binding myValue}
简单地绑定值


我的问题是:它们之间是否存在明显的差异,或者这是用户的偏好?

存在语义差异

  • 如果多个控件引用静态资源,则它们都引用同一对象
  • 如果将UI元素的
    DataContext
    设置为模型类的实例,则每个元素都会获得自己的实例

来说明,考虑这个模型类:

public class Model
{
    private static int counter;

    private readonly int id;

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

    public override string ToString()
    {
        return id.ToString();
    }
}
…以及一些使用它的XAML代码段:

<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>

...
输出:


用户偏好。您还可以将datacontext绑定到资源
DataContext={StaticResource viewmodel}
我都不使用,我总是在MainWindow的constructor.Convention中使用
this.DataContext=new MainViewModel()
。后者是更“正确”的方法。前者通常用于其他目的,因此,虽然您可以这样做,但这样做会很奇怪。
<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>