How to pass specific value to the converter parameter?

Boris picture Boris · Apr 18, 2011 · Viewed 97.9k times · Source

I have created a class Person that looks like this:

public class Person
{
    public enum GenderType
    {
        Female, 
        Male
    }

    public string Name
    {
        get; set;
    }

    public GenderType? Gender
    {
        get; set;
    }
}

Next, I created data template that is going to present objects of type Person.
Here's XAML code:

<DataTemplate 
    x:Key="personTemplate" 
    DataType="{x:Type model:Person}">
  <StackPanel>
    <RadioButton 
        Content="Female" 
        IsChecked="{Binding Path=Gender, 
                    Converter={StaticResource genderConverter}, 
                    ConverterParameter=???}"/>
    <RadioButton 
        Content="Male" 
        IsChecked="{Binding Path=Gender, 
                    Converter={StaticResource genderConverter}, 
                    ConverterParameter=???}"/>
    <RadioButton 
        Content="Not specified" 
        IsChecked="{Binding Path=Gender, 
                    Converter={StaticResource genderConverter}, 
                    ConverterParameter=???}"/>
  </StackPanel>
</DataTemplate>

Of course the ???s in the code won't work :) The problem is that I want to create a genderConverter converter which will compare the given value, i.e. personObject.Gender, against the given Person.GenderType value provided in the parameter and return true if the values match.

I don't know how to make the converter parameter pass Person.GenderType.Female, Person.GenderType.Male and null, for the first, second and third radio button, respectively.

Answer

Pavlo Glazkov picture Pavlo Glazkov · Apr 18, 2011

Try using x:Static markup extension:

<RadioButton 
        Content="Female" 
        IsChecked="{Binding Path=Gender, 
                    Converter={StaticResource genderConverter}, 
                    ConverterParameter={x:Static model:GenderType.Female}}"/>

OR, you could just pass a string and use Enum.Parse to convert that string to the enum type in the converter:

<RadioButton 
        Content="Female" 
        IsChecked="{Binding Path=Gender, 
                    Converter={StaticResource genderConverter}, 
                    ConverterParameter=Female}"/>

-

GenderType gender = (GenderType)Enum.Parse(typeof(GenderType), parameter.ToString());