Vishal Mistry
Vishal Mistry

Reputation: 376

Binding to TemplatedParent within a ControlTemplate.Resources

I have a ControlTemplate in which I would like to take in two collections and combine them into one collection which would then be bound to an ItemsControl.The calculation is done by the Calculator object, which I create an instance of within the ResourceDictionary of the template.

<Setter Property="Template">
  <Setter.Value>
    <ControlTemplate TargetType="{x:Type local:IndicatorBar}">
       <ControlTemplate.Resources>
          <local:Calculator 
            x:Key="_calculator"
            Ranges="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Ranges}" 
            DataSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DataSource}" />
        </ControlTemplate.Resources>

        <ItemsControl ItemsSource="{Binding Ratios, Source={StaticResource _calculator}}">
          <ItemsControl.ItemTemplate>
            <DataTemplate>
              <Border Background="{Binding Range}">
                <TextBlock Text="{Binding Ratio}" Foreground="White" />
              </Border>
            </DataTemplate>
          </ItemsControl.ItemTemplate>
        </ItemsControl>
      </ControlTemplate>
    </Setter.Value>
</Setter>

However, this does not seem to work and causes binding errors:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element.
BindingExpression:Path=Ranges; DataItem=null; target element is 'Calculator' (HashCode=33746798); target property is 'Ranges' (type 'Ranges')
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element.
BindingExpression:Path=DataSource; DataItem=null; target element is 'Calculator' (HashCode=33746798); target property is 'DataSource' (type 'IEnumerable')

I'm unsure of how I can get around this issue, so any help would be greatly appreciated!

Upvotes: 2

Views: 1465

Answers (1)

Thien Nguyen
Thien Nguyen

Reputation: 41

At first, your binding using RelativeSource.TemplatedParent mode so the source of the binding is the control that you apply this template. I don't think TemplatedParent is suitable for your case. Please refer to this link for TemplatedParent use. Could you add your model which contains your data for binding to Calculator control?

Upvotes: 0

Related Questions