C# WPF中Datacontext和ItemSource的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/801233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:44:47  来源:igfitidea点击:

Difference betwwen Datacontext and ItemSource in WPF

c#wpf.net-3.5

提问by Prashant Cholachagudda

Duplicate of :

重复:

Why are DataContext and ItemsSource not redundant?

为什么 DataContext 和 ItemsSource 不是多余的?



In WPF we can assign list of item to ComboBox in 2 ways

在 WPF 中,我们可以通过两种方式将项目列表分配给 ComboBox

//CODE #1
//WPF
<ComboBox name="cmbItems" ItemSource={Binding} />

//C#
cmbItems.DataContext = someList;

another way, directly assign itemsource

另一种方式,直接分配itemsource

//CODE #2
//WPF
<ComboBox name="cmbItems" ItemSource={Binding} />
//C#
cmbItems. ItemSource = someList;

both serves the purpose, but whats the difference in above snippet? and which is good to use?

两者都达到了目的,但是上面的代码片段有什么区别?哪个好用?

采纳答案by Gerrie Schenck

DataContext is mostly used on forms, controls etc.

DataContext 主要用于表单、控件等。

An ItemSource is a relative path to do databinding on that DataContext.

ItemSource 是对该 DataContext 进行数据绑定的相对路径。

For example when you make a form to edit Person details, then the DataContext would be Person and the different controls on the form will each bind on a seperate property on that object, for example Name, Date of Birth, etc.

例如,当您制作一个表单来编辑 Person 详细信息时,DataContext 将是 Person 并且表单上的不同控件将分别绑定到该对象的一个​​单独属性上,例如姓名、出生日期等。

回答by Arcturus

In the second example you can leave out the ItemsSource={Binding}.. You are setting the ItemsSource directly to a value in your code behind.. You won't need a binding here. In your first example, you set the DataContext, and use a binding to retrieve it again from the DataContext..

在第二个示例中,您可以省略 ItemsSource={Binding}.. 您将 ItemsSource 直接设置为后面代码中的值.. 此处不需要绑定。在您的第一个示例中,您设置了 DataContext,并使用绑定从 DataContext 中再次检索它。

But it doesn't really matter.. for both methods work fine...

但这并不重要......因为这两种方法都可以正常工作......

I use the following thumb of rule: set it in code behind, if I have the collection available.. Set it in some kind of binding mode, if I need to transform the collection, so that I can use a IValueConverter to do the job...

我使用以下规则经验:如果我有可用的集合,请将其设置在代码后面。如果我需要转换集合,请将其设置为某种绑定模式,以便我可以使用 IValueConverter 来完成这项工作...