开发者

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开发者_如何学Python '8'.

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


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;
}


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>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜