DataTemplates DataContext传递给其嵌套的UserControl [英] DataTemplates DataContext passed-through to its nested UserControl
问题描述
您好,
我的情况:对于我的ListBox'ListBoxItems,我在ResourceDictionary中定义了一个DataTemplate.此DataTemplate将由TemplateSelector选择.此DataTemplate包含一个UserControl.我想显示UserControl中ListBox的ItemsSource中的数据:如何将数据从DataTemplate传递到UserControl.
我的ListBox:
< ListBox ItemsSource =" { Binding Path = aXYCollection}"
ListBox.ItemTemplateSelector<
>我的ResourceDictionary中有什么: br>和我的UserControl:
< UserControl x:Class ="MyUserControl" />
</Grid>
</UserControl>
我希望DataContext将自动传递.但是UserControl的DataContext为null.当我直接在DataTemplate中使用Label时,它显示了属性的期望值: ; />
</DataTemplate>
但是我必须使用UserControl.如何传递DataContext?
感谢您的回答.
Hi there,
my scenario: for my ListBox' ListBoxItems I have defined in my ResourceDictionary a DataTemplate. This DataTemplate will be selected by a TemplateSelector. This DataTemplate contains a UserControl. I want to display the data from the ListBox' ItemsSource within the UserControl: how I can pass-through the data from the DataTemplate to the UserControl.
My ListBox:
<ListBox ItemsSource="{Binding Path=aXYCollection}">
<ListBox.ItemTemplateSelector>
<local:MyListBoxItemTemplateSelector />
</List>
</ListBox>
What I have in my ResourceDictionary:
<DataTemplate x:Key="myTemplate">
<uc:MyUserControl />
</DataTemplate>
And my UserControl:
<UserControl x:Class="MyUserControl">
<Grid>
<Label Content="{Binding MyProperty}" />
</Grid>
</UserControl>
I hoped the DataContext will be passed-through automatically. But the DataContext of the UserControl is null. When I use the Label directly within the DataTemplate, it shows the wished value of the property:
<DataTemplate x:Key="myTemplate">
<Label Content="{Binding MyProperty}" />
</DataTemplate>
But I have to use the UserControl. How I can pass-through the DataContext?
Thanks for your answers.
推荐答案
->但是我必须使用UserControl.我如何传递DataContext?我相信DataContext属性会正确地沿树传播,请您提供一个小而完整且可立即运行的示例,以演示如何做到这一点为您工作吗?
感谢
-> But I have to use the UserControl. How I can pass-through the DataContext?
I believe the DataContext property will get propagated down the tree correctly, could you please provide a small, complete and ready-to-run example to demonstrate how it doesn't work for you?
Thanks
这篇关于DataTemplates DataContext传递给其嵌套的UserControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!