How to multiply a value by a constant in WinRT XAML

The easiest way to accomplish this task is to use converter provided below. It is written in C++ but this convertor can be easily converted to C#:

[Windows::Foundation::Metadata::WebHostHidden]
public ref class MultiplicationConverter sealed : Windows::UI::Xaml::Data::IValueConverter
{
public:

    virtual Platform::Object^ Convert(Platform::Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^ parameter, Platform::String^ language);

    virtual Platform::Object^ ConvertBack(Platform::Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^ parameter, Platform::String^ language);

private:

    Platform::Object^ InternalConvert(Platform::Object^ value, Platform::Object^ parameter, bool forward);
};

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::UI::Xaml::Interop;

Object^ MultiplicationConverter::InternalConvert(Object^ value, Object^ parameter, bool forward)
{
    if (value != nullptr)
    {
        auto boxed_value = dynamic_cast<Box<float>^>(value);

        if (boxed_value == nullptr)
        {
            throw ref new InvalidArgumentException("Value passed to MultiplicationConverter is incorrect. Expected a value of type float.");
        }

        auto boxed_param = dynamic_cast<Box<float>^>(parameter);

        if (boxed_param == nullptr)
        {
            throw ref new InvalidArgumentException("Parameter of MultiplicationConverter is incorrect. Expected a value of type float.");
        }

        auto float_value = boxed_value->Value;

        auto float_param = boxed_param->Value;

        if (forward)
        {
            return float_value * float_param;
        }

        return float_value / float_param;
    }

    return nullptr;
}

Object^ MultiplicationConverter::Convert(Object^ value, TypeName targetType, Object^ parameter, String^ language)
{
    (void) targetType;    // Unused parameter
    (void) language;    // Unused parameter

    return InternalConvert(value, parameter, true);
}

Object^ MultiplicationConverter::ConvertBack(Object^ value, TypeName targetType, Object^ parameter, String^ language)
{
    (void) targetType;    // Unused parameter
    (void) parameter;    // Unused parameter
    (void) language;    // Unused parameter

    return InternalConvert(value, parameter, false);
}

Usage in XAML:

<TextBlock Text="Hello!" FontSize={Binding ElementName=rootControl,  Path=FontSize, 
    Converter={StaticResource multiplicationConverter}, ConverterParameter="1.5", Mode="OneWay"}"/>

Of cause, it is a trivial code, but probably someone will find it helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *