wpfivalueconverter

wpf Combobox and IValueConverter


I am relatively new to WPF and keep trying out little tests to improve my Knowledge. I am currently trying to utilise a Combobox to select an item and based upon the selection, change the color of the MainForm background utilising an IValueConverter as below:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if(value != null)
        {
            if (value.ToString() == "Male")
            {
                return new SolidColorBrush(Color.FromArgb(255, 27, 161, 226));
            }
            else
            {
                return new SolidColorBrush(Color.FromArgb(255, 216, 0, 115));
            }
        }
        return null;
    }

My problem is that the value is returning “System.Windows.Controls.ComboBoxItem: Female” Or System.Windows.Controls.ComboBoxItem: Male. What is the correct way to implement this comparison?

My full MainWindow Xaml is:

<Window x:Class="MVVM.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:MVVM"
    xmlns:m="clr-namespace:MVVM.Models"
    xmlns:vm="clr-namespace:MVVM.ViewModels"
    xmlns:converters="clr-namespace:MVVM.ViewModels.Converters"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.Resources>
    <m:Person x:Key="person"/>
    <converters:BackgroundConverter x:Key="converter"/>
    <vm:ViewModelBase x:Key="viewModel"/>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource person}}"
      Background="{Binding Gender, Converter={StaticResource converter}}">
    <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
        <TextBox Text="{Binding Name, Mode=TwoWay}"/>
        <TextBox Text="{Binding LastName, Mode=TwoWay}"/>
        <TextBlock Text="{Binding FullName}" FontSize="20"/>
        <ComboBox SelectedValue="{Binding Gender, Mode=TwoWay}">
            <ComboBoxItem>Male</ComboBoxItem>
            <ComboBoxItem>Female</ComboBoxItem>
        </ComboBox>
        <Button Content="Simple Command" Command="{Binding SimpleCommand, Source={StaticResource viewModel}}"/>
    </StackPanel>
</Grid>

Thank you for your assistance.


Solution

  • you can add Strings into ComboBox. ComboBoxItems will be created behind the scenes:

    <ComboBox SelectedValue="{Binding Gender, Mode=TwoWay}">
        <sys:String>Male</sys:String>
        <sys:String>Female</sys:String>
    </ComboBox>
    

    where sys in a namespace declaration:

    xmlns:sys="clr-namespace:System;assembly=mscorlib"