简体   繁体   中英

Accessing a resource from within the same resource dictionary in WPF

I have run into a scenario where I need to access a datatemplate defined within a usercontrol's resource dictionary from within a style in the same resource dictionary. The xaml code looks something like this:

<UserControl.Resources>
  <ResourceDictionary>
<DataTemplate x:Key="headertemp">
           <WrapPanel>
              <TextBlock Text="{Binding ProcedureName}"></TextBlock>
              <Label Content="{Binding Status}"></Label>
           </WrapPanel>
        </DataTemplate>
        <Style  TargetType="{x:Type ListBoxItem}">
           <Setter Property="Background" Value="Transparent"/>
           <Setter Property="Margin" Value="0,2,0,0"/>
           <Setter Property="Template">
              <Setter.Value>
                 <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Expander HeaderTemplate="{Binding Source={StaticResource headertemp}}">
                       <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Detail}" HeadersVisibility="Column">
                          <DataGrid.Columns>
                             <DataGridTextColumn Header="Timestamp" Binding="{Binding TimeStamp}"></DataGridTextColumn>
                             <DataGridTextColumn Header="Name" Binding="{Binding ProcedureName}"></DataGridTextColumn>
                             <DataGridTextColumn Header="Details" Binding="{Binding Description}"></DataGridTextColumn>
                          </DataGrid.Columns>
                       </DataGrid>
                    </Expander>
                 </ControlTemplate>
              </Setter.Value>
           </Setter>
        </Style>
  </ResourceDictionary>

This does not work. I figured the problem might be because both the datatemplate and the style are defined at the same 'level'. However, even if I move the style to the resourcedictionary of a lower level, say a grid, it does not work. I am not very used to WPF styles. Solutions different from the current one are also welcome. Thanks.

HeaderTemplate property expects the DataTemplate, not binding. So the following

<Expander HeaderTemplate="{Binding Source={StaticResource headertemp}}">

Should be

<Expander HeaderTemplate="{StaticResource headertemp}">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM