开发者

Double "1/3" as ConverterParameter

I have to convrt a double to other using a converter and a parameter:

This is my XAML stub:

Converter={StaticResource ToOtherDoubleConverter}, ConverterParameter=-1/2

this is the converter:

[ValueConversion(typeof(double), typeof(double))]
public class DoubleToOtherDoubleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
                  开发者_如何学Python        CultureInfo culture)
    {
        return (double)value * double.Parse(parameter.ToString());
    }

Now, this is useless to say that this is culture dependent, etc..

Is there a way to "hardcode" a double to be recognized as double? Because the above variant could be written in different ways, by eg.:

ConverterParameter=-1/2
ConverterParameter=-0.5
ConverterParameter=-0,5
etc.

or also

double.Parse(parameter.ToString());
(double)parameter;

etc...

One more question:

How can I specify 1/3 in the floating format? something like

ConverterParameter=0.333333333333333333333333333333333333333333333333333333


Unfortunetly not, the IValueConverter interface provides methods accepting object - which is not type save - instead of generics.
But you could add a Culture.InvariantCulture to your parse and throw an exception. This way you would notify the user about the "incorrect" format.


try this

public class DoubleToOtherDoubleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        var frac = ((string) parameter).Split('/');
        if (frac.Length == 2)
            return (double) value*double.Parse
                (frac[0])/double.Parse(frac[1]);
        return (double) value* double.Parse(((string) parameter)
            .Replace(",", "."));
    }

    public object ConvertBack(object value, Type targetType, 
        object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜