How to pass specific value to the converter parameter?
Solution 1
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());
Solution 2
Since you're creating your own converter why don't you just send a nullable bool as the converter parameter?
so for male,female,not specified
send true,false,null
.
If you don't want to do that you will have to reference your namespace in the beginning like this:
xmlns:myNamespace="clr-namespace:MyNamespace"
and then
<RadioButton
Content="Male"
IsChecked="{Binding Path=Gender,
Converter={StaticResource genderConverter},
ConverterParameter=x:Static myNamespace:Person.GenderType.Male}"/>
for your radiobuttons.
Boris
Updated on July 09, 2022Comments
-
Boris almost 2 years
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 agenderConverter
converter which will compare the given value, i.e.personObject.Gender
, against the givenPerson.GenderType
value provided in the parameter and returntrue
if the values match.I don't know how to make the converter parameter pass
Person.GenderType.Female
,Person.GenderType.Male
andnull
, for the first, second and third radio button, respectively. -
Mike over 4 yearsI would not cast an enum to a trenary for several reasons - it obscures the intended meaning of the enum, it makes the code less readable (i.e. was "male" true or false? and why?) and it limits the extension possibilities of the enum (or introduces problems when the enum gets extended in the future).