Using a TemplateBinding in ControlTemplate.Triggers

夙愿已清 提交于 2021-02-06 09:50:53

问题


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?


回答1:


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."




回答2:


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.



来源:https://stackoverflow.com/questions/9281579/using-a-templatebinding-in-controltemplate-triggers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!