12

what I am trying to do is relatively simple. I am just trying to bind the Y element of a TranslateTransform on an ellipse to 1/2 the height of the ellipse:

    <Ellipse Name="EllipseOnlyLFA" Height="200" Fill="Yellow" HorizontalAlignment="Left" VerticalAlignment="Bottom" ClipToBounds="True">
        <Ellipse.Width>
            <Binding ElementName="EllipseOnlyLFA" Path="Height"/>
        </Ellipse.Width>
        <Ellipse.RenderTransform>
            <TranslateTransform>
                <TranslateTransform.Y>
                    <Binding Converter="MultiplyByFactor" ElementName="EllipseOnlyLFA" Path="Height"  ConverterParameter="0.5"/>
                </TranslateTransform.Y>
            </TranslateTransform>
        </Ellipse.RenderTransform>
    </Ellipse>

I also have the following converter:

public class MultiplyByFactor : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((double)value * (double)parameter);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return true;
    }
}

I am getting an error on the XAML line where I actually use the converter. The error is

'Set property 'System.Windows.Data.Binding.Converter' threw an exception.' Line number '22' and line position '8'.

Can anyone shed some light on how to do this? EDIT: Yes, I have the converter added as a resource.

Adam S
  • 8,945
  • 17
  • 67
  • 103

3 Answers3

17

You need to add the converter to the resources

Edit
You need to add the namespace too

    xmlns:c="clr-namespace:WpfApplication1"

end edit

<Window.Resources>
    <c:MultiplyByFactor x:Key="myMultiplyByFactor"/>
</Window.Resources>

Then you can use the instance from the resources

<TranslateTransform.Y>
    <Binding Converter={StaticResource myMultiplyByFactor}"
        ElementName="EllipseOnlyLFA"
        Path="Height" ConverterParameter="0.5"/>
</TranslateTransform.Y>
poudigne
  • 1,694
  • 3
  • 17
  • 40
Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
17

There are 2 thing wrong with your code

1) your converter needs to be accessed using the StaticResource declaration

<Binding Converter="{StaticResource myMultiplyByFactor}" 
    ElementName="EllipseOnlyLFA" Path="Height"  ConverterParameter="0.5"/

2) Your converter parameter is a string by default, so you need to convert it to a double

public object Convert(object value, Type targetType, 
    object parameter, CultureInfo culture)
{
    double.TryParse((parameter as string).Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out double param);
    return param * (double)value;
}
Coden
  • 2,579
  • 1
  • 18
  • 25
Dean Chalk
  • 20,076
  • 6
  • 59
  • 90
0

The Parameter probably gets passed as a String. Set a breakpoint in your Converter and look at the values of value and parameter. You might need to use double.Parse instead of the cast.

Jens
  • 25,229
  • 9
  • 75
  • 117