标签:des style blog http io ar color os 使用
此段为原文翻译而来,原文地址
WPF 中 数据绑定 ItemSource和 DataContext的不同点:
1.DataContext 一般是一个非集合性质的对象,而ItemSource 更期望数据源是 集合对象。
2.DataContext 是 FrameworkElement 类中定义的一个依赖属性(Dependency property),ItemsSource是 在ItemsControl 类中定义的。所有继承自FrameworkElement 的类(控件)都可以使用DataContext属性并给其赋值,但我们只能给ItemsSource赋值为集合对象
3.DataContext不能产生模板,它只能用来筛选出数据,供其它控件来绑定。而ItemsSource主要作用就是给模板提供数据。
4.DataContext主要用来抓取一些子元素需要使用的数据,以保证子元素能够顺利的使用数据。ItemsSource不会用来分享数据,它只是对定义好的元素有效。
第四点的实在不知道如何翻译。最后附上原文。
In this post I will try to illustrate the difference between DataContext and ItemsSource property in Silverlight/WPF. These two properties don‘t serve the same purpose.
Examples:
Suppose we have a Person Class which has a property Name. Now in Xaml we can say like:
<StackPanel x:Name="Parent"> <StackPanel.Resources> <local:Person x:Key="person"> </StackPanel.Resources> <ListBox ItemsSource="{Binding Source={StaticResource person}}"> <ListBox.ItemTemplate> <DataTemplate> <TextBox Text="{Binding Path=Name}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </StackPanel>
If you run this code in the ListBox you will get to see values depending on List<Person> object. But if we change the ItemsSource to DataContext then you will be not able to see anything because DataContext doesn‘t generate templates in any cases. If you set datacontext still you have to set the ItemsSource property like this:
<ListBox DataContext="{Binding Source={StaticResource person}}" ItemsSource="{Binding}">
Conclusion:
In a word, if we have several child elements that will share a common data source, we can set DataContext property for the parent elements. And we use ItemsSource for ItemsSource in most cased to generate template. Like:
<StackPanel DataContext="{Binding Person"}> <TextBox Text="{Binding FName}"/> <TextBox Text="{Binding LName}"/> </StackPanel>
WPF中 ItemsSource 和DataContext不同点
标签:des style blog http io ar color os 使用
原文地址:http://www.cnblogs.com/flytigger/p/4113121.html