ExpressionConverter support string comparison?

Aug 28, 2012 at 9:18 PM
Edited Aug 28, 2012 at 9:22 PM

I was hoping to use the ExpressionConverter to perform a string comparison:

IsEnabled="{Binding Path=, Converter={con:ExpressionConverter {}{0}=='Custom'}}"

This does't work and gives the error: The argument name is missing.  Can ExpressionConverter be used in some fashion like this?  If not, might this be considered for a future release?

I found a workaround using the MapConverter as such:

<MenuItem.IsEnabled>
    <Binding>
        <Binding.Converter>
            <con:MapConverter>
                <con:Mapping From="Required">
                    <con:Mapping.To>
                        <System:Boolean>False</System:Boolean>
                    </con:Mapping.To>
                </con:Mapping>
                <con:Mapping From="Custom">
                    <con:Mapping.To>
                        <System:Boolean>True</System:Boolean>
                    </con:Mapping.To>
                </con:Mapping>
            </con:MapConverter>
        </Binding.Converter>
    </Binding>
</MenuItem.IsEnabled>

Thanks.

Coordinator
Sep 3, 2012 at 9:37 AM

This is a supported scenario, but there are several syntactic problems with your code. Unfortunately, embedding expressions in XAML can be a bit of a nightmare, so it's often best to just place it inside a CDATA section:

    <Button>
        <Button.IsEnabled>
            <Binding>
                <Binding.Converter>
                    <con:ExpressionConverter>
                        <![CDATA[
                        {0} == "Custom"
                        ]]>
                    </con:ExpressionConverter>
                </Binding.Converter>
            </Binding>
        </Button.IsEnabled>
    </Button>

Of course, if you need this more than once (or even if you just prefer this aesthetically) you can define the converter as a resource and reference it from your binding:

    <Window.Resources>
        <con:ExpressionConverter x:Key="IsCustomConverter">
            <![CDATA[
            {0} == "Custom"
            ]]>
        </con:ExpressionConverter>
    </Window.Resources>
    
    <Button IsEnabled="{Binding Converter={StaticResource IsCustomConverter}}"/>

HTH,
Kent