Sends for the fellow dear visitors:welcome to dongpad!


 Welcome to DongPad!

 msn


Difference between DataContext and ItemsSource in

今天在尝试SL的Binding时,发现对ListBox仅设置DataContext不能起到作用,XAML代码如下:

<ListBox Grid.Row="2"
         Height="76"
         HorizontalAlignment="Left"
         Margin="311,35,0,0"
         Name="listBox_TemperatureList"
         VerticalAlignment="Top"
         Width="219"
         DataContext="{StaticResource thermastatKey}"
         ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal"> 
                <Image Source="{Binding TempImage}" Width="16" Height="16"/>
                <TextBlock Text="{Binding Temperature,Converter={StaticResource temperatureConverterKey}}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

有问题找Google,发现有这个疑惑的还不少,参见.NET Framework Developer Center得出的结论是:

DataContext是所有FrameworkElement及其子类型的通用依赖属性。可以在逻辑树种从父节点继承,并且隐式的用于数据绑定。但是只有在ItemsSource属性制定后,WPF才会生成数据模板。而设置DataContext不会自动生成模板。

原文如:

DataContext is a general (dependency) property of all descendants of FrameworkElement. Is is inherited through the logical tree from parent to children and can be used as an implicit source for DataBinding. It does not do anything by itself, you must basically databind to it.



评论: 0 | 引用: 0 | 查看次数: 1218 | 返回顶部
发表评论
昵 称:    
验证码:   
 
内 容:
选 项:  
 
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 500 字 | UBB代码 开启 | [img]标签 开启