WPF中的DataTemplate和DataContext有什么区别? [英] What is the difference between DataTemplate and DataContext in WPF?

查看:59
本文介绍了WPF中的DataTemplate和DataContext有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过以下 DataContext 语法设置视图模型与视图之间的关系:

I can set the relationship between View Model and view through following DataContext syntax:

 <UserControl.DataContext>
    <view_model:MainMenuModel />
</UserControl.DataContext>

我还可以通过以下 DataTemplate 语法设置视图模型与视图之间的关系:

And I can also set the relationship between View Model and view through following DataTemplate syntax:

    <DataTemplate
        DataType="{x:Type viewModel:UserViewModel}">
        <view:UserView />
    </DataTemplate>

两者之间有什么区别?第二个 XAML 是否未设置视图的数据上下文?

What is the difference between the two? Is the second XAML not setting the data context of a view?

推荐答案

您的第二个XAML定义了一个 template ,可用于显示 viewModel:UserViewModel 类型的对象.它不会设置任何数据,但是,如果要求 ContentPresenter 显示该类型的对象,它将使用您的模板.

Your second XAML defines a template that can be used to display an object of type viewModel:UserViewModel. It doesn't set data for anything but, if a ContentPresenter is asked to display an object of that type, it will use your template.

您的第一个XAML设置控件的 DataContext 属性.它定义了您在该范围内执行的任何绑定都将使用 DataContext 作为绑定的根(除非显式覆盖).对于工作中的 DataContext 的简单示例,请比较这两个(均假定"s"是 System 命名空间):

Your first XAML is setting the DataContext property of your control. It defines that any bindings you perform within that scope will use the DataContext as the root of the binding (unless explicitly overriden). For a simple example of DataContext at work, compare these two (both assume that "s" is the System namespace):

<StackPanel>  
  <TextBlock Text="{Binding Day, Source={x:Static s:DateTime.Now}}" />
  <TextBlock Text="{Binding Month, Source={x:Static s:DateTime.Now}}" />
  <TextBlock Text="{Binding Year, Source={x:Static s:DateTime.Now}}" />
</StackPanel>

<StackPanel DataContext="{Binding Source={x:Static s:DateTime.Now}}">  
  <TextBlock Text="{Binding Day}" />
  <TextBlock Text="{Binding Month}" />
  <TextBlock Text="{Binding Year}" />
</StackPanel>

StackPanels 都将相同地呈现,但是第二个更易于重用.(例如:如果您要显示其他日期,则只需在一个地方更改绑定.)

Both StackPanels will render identically, but the second is more easily reused. (E.g.: you only have to change the binding in one place if you wanted to display a different date.)

这篇关于WPF中的DataTemplate和DataContext有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆