Access DataContext Properties Inside ItemTemplate

I have a very nasty problem with bindings. I know that there are other topics regarding binding itmes inside an itemtemplate to the datacontext of an object outside the template. However, this simply will not work, i.e. The first text block displays β€œTest” as desired, while the same text block inside the itemtemplate does not show anything.

  <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 help here because it is really a problem for me.

+3
source share
1 answer

Inside an itemchemplate element, the binding is initialized by the context of the current element in AllItems.

Update

Outside ItemTemplateyour bindings relate to the DataContext of the page. **

ItemTemplate , .

, ( ):

<ItemsControl x:Name="myList" ItemsSource="{Binding AllItems}" >
    <ItemsControl.ItemTemplate>
         <DataTemplate>
             <StackPanel>
                 <TextBlock x:Name="tb1"
                        Text="{Binding DataContext.Test, ElementName=myList}"/>
                 <TextBlock x:Name="tb2" Text="{Binding KeyName}"/>
             </StackPanel>
         </DataTemplate>
     </ItemsControl.ItemTemplate>
 </ItemsControl>

tb1 DataContext.
tb2 cann access KeyName - , AllItems IEnumerable of .

, itemtemplate , , , ( ElementName ).

Test , .

, - , , , , .

** , ItemsControls ( )

+4

Source: https://habr.com/ru/post/1789372/


All Articles