Search code examples
visual-c++windows-runtimeconvertersivalueconverterc++-cx

How do I use ConverterParameter in C++/Cx?


I started a new Visual C++ project in Visual Studio and as part of the template, I got a BooleanToVisibilityConverter. This works fine, but it doesn't seem to honor ConverterParameter=Invert when specified.

XAML:

<UserControl.Resources>
    <local:IntToVisibilityConverter x:Name="IntToVisibilityConverter" />
    <common:BooleanToVisibilityConverter x:Name="BoolToVisibilityConverter" />
</UserControl.Resources>

...

<Image Width="24" Height="24" Source="/Assets/DisclosureTriangleDown.png" Visibility="{Binding Disclosed, Converter={StaticResource BoolToVisibilityConverter}}" />
<Image Width="24" Height="24" Source="/Assets/DisclosureTriangleRight.png" Visibility="{Binding Disclosed, Converter={StaticResource BoolToVisibilityConverter}, ConverterParameter=Invert}" />

C++:

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

    auto boxedBool = dynamic_cast<Box<bool>^>(value);
    auto boolValue = (boxedBool != nullptr && boxedBool->Value);
    return (boolValue ? Visibility::Visible : Visibility::Collapsed);
}

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

    auto visibility = dynamic_cast<Box<Visibility>^>(value);
    return (visibility != nullptr && visibility->Value == Visibility::Visible);
}

I'm assuming I need to do something with the Object^ parameter variable, but what? And why doesn't the built-in project template handle this case?


Solution

  • The converter parameter is an optional, additional parameter a XAML consumer would pass to the converter to specify context-specific details of the conversion.

    It would be up to you, as the author of the converter, to designate how exactly this parameter worked (and to implement the logic for it using the parameter). Basically, you would need to cast the Object^ parameter to a String^ and then compare it with "Invert" (and then change the behavior of your Convert functions to behave accordingly).

    This blog post has more information; it is about WPF but the concepts are the same: http://zamjad.wordpress.com/2010/01/08/passing-parameters-to-value-converter/