-2

I have two controls that contain identical markup, except that they require different converters.

LeftHeader.xaml snippet:

<Path.RenderTransform>
    <RotateTransform Angle="{Binding IsToggled, Converter={x:Static local:LeftHeader.GlyphAngleConverter}}"/>
</Path.RenderTransform>

RightHeader.xaml snippet:

<Path.RenderTransform>
    <RotateTransform Angle="{Binding IsToggled, Converter={x:Static local:RightHeader.GlyphAngleConverter}}"/>
</Path.RenderTransform>

I thought I could create a UserControl with a DependencyProperty of type IValueConverter called "GlyphAngleConverter" and this markup:

<UserControl x:Class="GlyphControl"
    <UserControl.Template>
        <ControlTemplate>
            
            ...
            
                <Path.RenderTransform>
                    <RotateTransform Angle="{Binding IsToggled, Converter={TemplateBinding GlyphAngleConverter}}"/>
                </Path.RenderTransform>
            
            ...
            
        </ControlTemplate>
    </UserControl.Template> 
</UserControl>

The header controls would then use the new control and set GlyphAngleConverter basically like they used before:

New LeftHeader.xaml snippet:

<GlyphControl GlyphAngleConverter="{Binding Source={x:Static local:LeftHeader.GlyphAngleConverter}}"/>

New RightHeader.xaml snippet:

<GlyphControl GlyphAngleConverter="{Binding Source={x:Static local:RightHeader.GlyphAngleConverter}}"/>

But I get the exception "Unable to cast object of type 'System.Windows.TemplateBindingExpression' to type 'System.Windows.Data.IValueConverter'."

What am I doing wrong and/or is there a better approach?

mike
  • 1,627
  • 1
  • 14
  • 37
  • 1
    You can not bind the Converter of a Binding. Perhaps use a MultiBinding as shown here: https://stackoverflow.com/a/15309844/1136211 – Clemens Feb 05 '23 at 16:54

2 Answers2

1

As pointed out in the comments, "You can not bind the Converter of a Binding.".

My solution: create a UserControl with a DependencyProperty of type double called "GlyphAngle" and use that in the header controls, e.g.:

 <GlyphControl GlyphAngle="{Binding IsToggled, Converter={x:Static local:LeftHeader.GlyphAngleConverter}}"/>

So, instead of passing the converter into the control, I'm passing the converted value.

mike
  • 1,627
  • 1
  • 14
  • 37
-1

You could try defining your converter as a resource.

Do so in a resource key merged in app.xaml. Then define your "other" converter in the the resources of one of the usercontrols, with the same key that is in a resource key merged in app.xaml.

If you have two resources with the same key then whichever is the most local will be found.

The "local" converter will be found in one usercontrol and the global in the other.

Andy
  • 11,864
  • 2
  • 17
  • 20