WPF DataTemplate Textblock binding

左心房为你撑大大i 提交于 2019-12-23 03:51:59

问题


I have a listbox of Students and the datatemplate for list item. The DataTemplate has a text block named tb. I want to set this textblock to be binded to Name property. How can I do it in xaml form outside? (Not from the datatemplate)

<ListBox ItemsSource="{Binding l}"      ItemTemplate="{Binding DataTemplate_L}" Margin="12,70,0,0">

</ListBox>

Thank you


回答1:


If I understand you correctly, you're asking how you set the databinding for the textblock, that is currently in your DataTemplate? You can't set that databinding at the ListBox level; it has to be done in your DataTemplate.

In this case the DataTemplate will inherit the DataContext of each item in the list.

<DataTemplate x:Key="myDataTemplate">
    <StackPanel>
       <TextBlock Text="{Binding Path=Name}" />
       <TextBlock Text="{Binding Path=AnotherListItemProperty}" />
    </StackPanel>
</DataTemplate>

In other words - this DataTemplate is a template for each item in the list - and the DataContext will be each item in the list.



来源:https://stackoverflow.com/questions/27231838/wpf-datatemplate-textblock-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!