Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a TemplateBinding in ControlTemplate.Triggers

Tags:

.net

wpf

Why does the following piece of XAML give me a XamlParseException with the (meaningless) message "Expression type is not a valid Style value." at runtime?

<Control x:Class="TestApp.Max.MyControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:Max="clr-namespace:TestApp.Max"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
  <Control.Template>
    <ControlTemplate>
      <TextBlock Name="txt" Text="{TemplateBinding Max:MyControl.Foo}" />
      <ControlTemplate.Triggers>
        <Trigger Property="Control.IsMouseOver" Value="True">
          <Setter TargetName="txt" Property="Text" Value="{TemplateBinding Max:MyControl.Bar}" />
        </Trigger>
      </ControlTemplate.Triggers>
    </ControlTemplate>
  </Control.Template>
</Control>

The offending line is

<Setter TargetName="txt" Property="Text" Value="{TemplateBinding Max:MyControl.Bar}" />

If I replace the TemplateBinding with a normal Binding it starts to work:

{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text2}

Shouldn't I be able to use a TemplateBinding since I am within a ControlTemplate? And what does the exception message really mean?

like image 433
stmax Avatar asked Feb 14 '12 17:02

stmax


2 Answers

Binding TemplatedParent: In this line the value of the path2 is going to apply for the Text property of the TextBlock, so it runs fine.

In TemplateBinding : Have a close look at this, The resolved value of the Max:MyControl.Bar is going to act as the resource key for the Template binding [Here the value of Bar is not an actual value, instead it s a property key name ] which doesnt exists and so it throws the error "The given key was not present in the dictionary."

like image 79
Sivasubramanian Avatar answered Oct 14 '22 10:10

Sivasubramanian


Triggers work best when defined in stand-alone styles, not in-place content. Try defining your trigger in a style resource, then reference the style resource from your template.

like image 32
dthorpe Avatar answered Oct 14 '22 09:10

dthorpe