I have a really nasty problem with bindings. I know that there are other topics regarding binding itmes inside itemtemplate to datacontext of an object outside the template. However, this just won’t work, i.e. the first textblock display ‘Test’ as desired whereas the same textbox inside the itemtemplate shows nothing.
<TextBlock Text="{Binding DataContext.Test, ElementName=myList}"/>
<ItemsControl x:Name="myList" ItemsSource="{Binding AllItems}"
Margin="0,0,0,0" VerticalAlignment="Top" HorizontalAlignment="Center">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel Orientation="Horizontal"
ItemHeight="170" ItemWidth="140"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image x:Name="{Binding KeyName}"
Source="{Binding ImagePath}"
Width="128"
Height="128">
</Image>
<TextBlock Text="{Binding DataContext.Test, ElementName=myList}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
I would appreciate some help here folks as this is really a problem for me.
Inside the itemtemplate, the binding is initialized to the context of the current item in
AllItems.Update
Outside of the
ItemTemplateyour bindings are relative to the DataContext of the page.**Once inside an
ItemTemplatethen bindings are limited to the scope of the item specifically being evaluated at that time.So, if we assume the following (based on the code in your question):
tb1cannot access the DataContext object directly.tb2cann accessKeyName– assuming that whatever objectAllItemsis an IEnumerable of contains a property with that name.As I understand it, inside an itemtemplate, the item past from the enumeration controls the binding source and this can’t be overridden (by setting ElementName or otherwise).
If you need the value from
Testin every object in your enumeration then you’ll need to add it as a property of the object in the enumeration.I’m sure someone more knowledgeable than me could explain why this is or give a better explanation but that’s the gist of it.
** Assuming no other nesting of ItemsControls (or equivalent)