Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a WPF ComboBox as listed below

C#
<ComboBox Grid.Column="1" Grid.Row="3" Style="{StaticResource FormComboBox}" SelectedItem="{Binding Gender}">
  <ComboBoxItem Content="Male" Tag="M"/>
  <ComboBoxItem Content="Female" Tag="F"/>
  <ComboBoxItem Content="Other" Tag="O"/>
</ComboBox>


I want to bind the value of the Tag attribute of the selected item to the ViewModel property "Gender"

C#
private char _gender;
public char Gender
{
  get { return _gender; }
  set { _gender = value; NotifyPropertyChanged(nameof(Gender)); }
}


What I have tried:

As you can see I tried binding to the SelectedItem
Posted
Updated 10-Feb-23 10:54am
Comments
Graeme_Grant 10-Feb-23 16:16pm    
Is the DataContext set? Do you have any errors in the DataBindingFailures Debug Windows?
Christopher Fernandes 10-Feb-23 16:27pm    
Yes the DataContext is set and there are no errors

1 solution

Binding to a Tag is not how I would do it.

But, as this is how you want to, will need to write an IValueConverter[^] to work with the Tag property:
C#
public class CharConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((char)value) switch

        {
            'M' => "Male",
            'F' => "Female",
            _ => "Other"
        };
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((ComboBoxItem)value).Tag;
    }
}

and to use:
XML
<Grid>
    <Grid.Resources>
        <local:CharConverter x:Key="CharConverter" />
    </Grid.Resources>
    <ComboBox SelectedItem="{Binding Gender,
                             Converter={StaticResource CharConverter}}"
              HorizontalAlignment="Center"
              VerticalAlignment="Center"
              Width="100">
        <ComboBoxItem Content="Male" Tag="M"/>
        <ComboBoxItem Content="Female" Tag="F"/>
        <ComboBoxItem Content="Other" Tag="O"/>
    </ComboBox>
</Grid>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900