XAML: How to use a ConverterParameter which is not a string in XAML?

Imagine the following case: I have a TextBox and a TextBlock and a boolean property IsEditing.

If IsEditing is true, the TextBox is visible and the TextBlock is hidden and reversely.

In this case I could use a ViewModel with two properties of type Visibility and the problem would be solved.

However in this post, I want to use with Converters.

The problem is the fact that I have only one boolean property and that Visibility controls property are both bound to it with different behaviors.

So I will use a ConverterParameter to differentiate them.

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    return ((bool)value ^ (parameter != null && (bool)parameter)) ? Visibility.Visible : Visibility.Collapsed;
}


The problem in my binding is the fact that I can’t write this:



Visibility="{Binding IsEditing, Converter={StaticResource BooleanToVisibilityConverter}, ConverterParameter=True}"


Indeed, with it, the parameter is a string and not a boolean as expected.



Of course I can make the binding to solve this by code but it isn’t the goal of this post.



So how to do it in xaml?



Like this:



<TextBlock.Visibility>
    <Binding Path="IsEditing"
            Converter="{StaticResource BooleanToVisibilityConverter}">
        <Binding.ConverterParameter>
            <system:Boolean>True</system:Boolean>
        </Binding.ConverterParameter>
    </Binding>
</TextBlock.Visibility>


Hope that helps

This entry was posted in 13461, 14489, 8708. Bookmark the permalink.

4 Responses to XAML: How to use a ConverterParameter which is not a string in XAML?

  1. I like the way, you did it so easily with the help of convertors
    Thanks :)

  2. nmclean says:

    WPF needs to convert strings to boolean whenever you write them in XAML. When you write ‘IsEnabled=”True”‘ for example, this is what is called behind the scenes:

    System.ComponentModel.TypeDescriptor.GetConverter(typeof(bool)).ConvertFrom(“True”)

    So, you can easily use the same method in your converter to allow users to simply write ‘ConverterParameter=True’ in XAML.

    In the case of boolean, there is actually a simpler method:

    System.Convert.ToBoolean(value)

    Or, if you’re using VB.NET:

    CBool(value)

  3. joazlazer says:

    THANKS SO MUCH!
    I was having problems with this (giving a bool as a converter param) but now I understand!

    Have a really good day!

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>