Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAML Binding to a converter

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.

like image 218
Adam S Avatar asked Nov 23 '10 07:11

Adam S


2 Answers

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>
like image 70
Albin Sunnanbo Avatar answered Sep 20 '22 23:09

Albin Sunnanbo


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;
}
like image 24
Dean Chalk Avatar answered Sep 20 '22 23:09

Dean Chalk