开发者

How to set the RelativeSource in a DataTemplate that is nested in a HierarchicalDataTemplate?

开发者 https://www.devze.com 2022-12-26 04:05 出处:网络
I have the following XAML, that does all that it is supposed to, except that the MultiBinding on the FontSize fails on retrieving the Users (I see DependencyProperty.UnsetData when I set a breakpoint

I have the following XAML, that does all that it is supposed to, except that the MultiBinding on the FontSize fails on retrieving the Users (I see DependencyProperty.UnsetData when I set a breakpoint in the converter). As you can see Users is an IEnumerable<UserData> that is part of the HierarchicalDataTemplate's DataContext.

How do I reference it??

<TreeView Name="AllGroups" ItemsSource="{Binding}" >
      <TreeView.Resources>
           <HierarchicalDataTemplate DataType="{x:Type PrivateMessengerUI:GroupContainer}"
                                     ItemsSource="{Binding Users}"
                                                  >
                  <Label Content="{Binding GroupName}"/>
            </HierarchicalDataTemplate>
            <DataTemplate DataType="{x:Type PrivateMessenger:UserData}">
               <TextBlock Text="{Binding Username}"
                          ToolTip="{StaticResour开发者_如何学编程ce UserDataGroupBox}"
                          Name="GroupedUser"
                          MouseDown="GroupedUser_MouseDown">
                    <TextBlock.FontSize>
                         <MultiBinding Converter="{StaticResource LargeWhenIAmSelected}">
                               <Binding ElementName="Root" Path="SelectedUser"/>
                               <Binding RelativeSource="???"
                                        Path="DataContext.Users"/>
                         </MultiBinding>
                     </TextBlock.FontSize>
               </TextBlock>
           </DataTemplate>
         </TreeView.Resources>
      </TreeView>


The correct answer is:

<Binding RelativeSource="{RelativeSource FindAncestor,
                                         AncestorType={x:Type TreeViewItem},
                                         AncestorLevel=2}"
                           Path="DataContext.Users"/>

The ancestorlevel is crucial and deceptive: when you omit it, a level of 1 is assumed and that actually points to the container of the DataTemplate (which is a childless TreeViewItem too!), not the container of the HierarchicalDataTemplate.


Í don't have access to an IDE to try it out (holdays...), but I'd try using the FindAncestor mode, like this:

RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type PrivateMessengerUI:GroupContainer}}

This should go up the logical tree to find the group container.

0

精彩评论

暂无评论...
验证码 换一张
取 消