简体   繁体   English

WPF XAML:DataContext作为XAML元素的属性还是属性之间的区别?

[英]WPF XAML: Difference between DataContext as attribute or property for XAML element?

I'm currently getting started with XAML and I have a question regarding how to define the DataContext of an element. 我目前正开始使用XAML,并且对如何定义元素的DataContext有疑问。

I've created a View that includes a Page with the following markup: 我创建了一个包含带有以下标记的页面的视图:

<Page x:Class="View.MainView"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:ViewModel="clr-namespace:ViewModel"
  mc:Ignorable="d"
  Title="MainView">
  ...
  </Page>

When I want to give this Page a DataContext to be used by child elements, this works: 当我想给此页面一个供子元素使用的DataContext时,此方法有效:

<Page x:Class="View.MainView"
  ...
  mc:Ignorable="d"
  Title="MainView">
  <Page.DataContext>
    <ViewModel:MainViewModel />
  </Page.DataContext>
  ...
  </Page>

And this doesn't: 而且这不是:

<Page x:Class="View.MainView"
  ...
  mc:Ignorable="d"
  Title="MainView" DataContext="ViewModel:MainViewModel">
  ...
  </Page>

For me, it looks like the Page element expects the DataSource to be defined as a XAML property and not as an attribute. 对我来说,Page元素希望将DataSource定义为XAML属性而不是属性。 However, the IntelliSense in Visual Studio offers me a DataContext attribute for the Page, so I guess I'm just using a wrong syntax here. 但是,Visual Studio中的IntelliSense为Page提供了DataContext属性,所以我想我在这里使用了错误的语法。 Can you point that out to me? 你能指出给我吗?

Thanks! 谢谢!

You can use the attribute to specify the DataContext , but you should consider how does your viewmodel get instantiated. 可以使用该属性指定DataContext ,但应考虑如何实例化您的viewmodel。

Using a property in this way 以这种方式使用属性

<Page.DataContext>
     <ViewModel:MainViewModel />
</Page.DataContext>

you tell WPF to instantiate the MainViewModel and to assign the created object to the DataContext property of the Page . 您告诉WPF实例化MainViewModel并将创建的对象分配给PageDataContext属性。

With an attribute, you just specify a string in that case: 使用属性,您只需在这种情况下指定一个string

DataContext="ViewModel:MainViewModel"

But you want WPF to create an instance for you. 但是您希望WPF为您创建一个实例。

So you can use eg a Binding or a StaticResource / DynamicResource to assign a created instance to the DataContext property: 因此,您可以使用BindingStaticResource / DynamicResource将创建的实例分配给DataContext属性:

DataContext="{Binding ViewModel}"

or 要么

<Page DataContext="{StaticResource ViewModel}">
    <Page.Resources>
        <ViewModel:MainViewModel x:Key = "ViewModel"/>
    </Page.Resources>
</Page>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM