它非常简单。
DataContext引用项目的相同属性。它没有得到扩展,也没有动态。 DataContext适用于当前位于父级内的子级属性。
但是ItemsSource是动态的。它随着源代码而延伸。这是一个例子。
这是一个示例xaml。
<UserControl x:Class="SilverlightApplication"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.Resources>
<DataTemplate x:Key="template2">
<StackPanel Orientation="Horizontal">
<Image x:Name="img1" Source="{Binding Image}"></Image>
<TextBlock x:Name="data2" Text="{Binding Data}"></TextBlock>
</StackPanel>
</DataTemplate>
</Grid.Resources>
<StackPanel>
<StackPanel x:Name="DataContextStack" Orientation="Vertical">
<TextBlock x:Name="data1" Text="{Binding Text1}"></TextBlock>
<TextBlock x:Name="data2" Text="{Binding Text2}"></TextBlock>
</StackPanel>
<ListBox x:Name="lst2" ItemTemplate="{StaticResource template2}"></ListBox>
</StackPanel>
</Grid>
这里是后面的代码。
namespace SilverlightApplication
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
loadLists();
}
private void loadLists()
{
ObservableCollection<Temp2> tColl = new ObservableCollection<Temp2>();
Temp1 t1 = new Temp1();
t1.Text1 = "DataContext1";
t1.Text2 = "DataContext2";
tColl.Add(new Temp2() { Image = "", Data = "Item1" });
tColl.Add(new Temp2() { Image = "", Data = "Item2" });
DataContextStack.DataContext = t1;
lst2.ItemsSource = tColl;
}
}
public class Temp1
{
public string Text1 { get; set; }
public string Text2 { get; set; }
}
public class Temp2
{
public string Image { get; set; }
public string Data { get; set; }
}
}
正如你所看到的,在DataContext适用于哪些存在的StackPanel中和是指一个单独的属性,该属性是文本的的TextBlocks。
而ItemsSource指的是Textblock的Image和Text属性的来源,并且列表中的项目可以与ObservableCollection一起扩展。
或者让它变得更简单。
DataContext - 根据设计设置值。 ItemsSource - 根据逻辑设置值。
希望这会有所帮助。
将此标记为答案,如果这回答了您的问题。
对于SelectedValue SelectedItem,如果我们有绑定,那么它将绑定到组合框的datacontext属性(而不是组合框的itemssource中每个项目的属性)。所以它是播放器的属性,现在是组合框的数据上下文 对于SelectedValuePath,DisplayMemberPath:我们不使用标记语法将值分配给它们,因此它基本上没有绑定。这就是为什么我们仍然可以在itemssource中分配项目属性的名称(而不是datacontext的属性)。我对吗? – Tai 2010-08-19 22:08:23