Question

I have the following scenario

1- A combobox in xaml

<ComboBox 
x:Name="PublishableCbo" Width="150" IsEnabled="True" HorizontalAlignment="Left" Height="20" 
SelectedValue="{Binding Path=Published, Mode=TwoWay}"
Grid.Column="6" Grid.Row="0">
<ComboBox.Items>
    <ComboBoxItem Content="All"  IsSelected="True" />
    <ComboBoxItem Content="Yes"  />
    <ComboBoxItem Content="No"  />
</ComboBox.Items>

2- In a model class, I defined a property and bind to the selectedvalue in combobox

 public bool Published
    {
      get
      {
        return _published;
      }
      set
      {
        _published = value;
        OnPropertyChanged("Published");
      }
    }

I know I have to implement a converter, but don't know exactly how. What I want is when a select Yes/No, in the model get a True/false value, when "all" is selected, to get null value.

Was it helpful?

Solution

In order to be able to assign null to the Published property, you would have to change its type to Nullable< bool > (you can write bool? in C#).

public bool? Published
{
    ...
}

The Converter could be implemented so that it converts from string to bool and vice versa, perhaps like shown below. Note that the converter uses bool, not bool? since the value is passed to and from the converter as object, and hence boxed anyway.

public class YesNoAllConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        object result = "All";

        if (value is bool)
        {
            result = (bool)value ? "Yes" : "No";
        }

        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        object result = null;

        switch ((string)value)
        {
            case "Yes":
                result = true;
                break;
            case "No":
                result = false;
                break;
        }

        return result;
    }
}

To enable the use of this converter, you have to change your ComboBox item type to string, and bind to the SelectedItem property, not SelectedValue.

<ComboBox SelectedItem="{Binding Path=Published, Mode=TwoWay,
                         Converter={StaticResource YesNoAllConverter}}">
    <sys:String>All</sys:String>
    <sys:String>Yes</sys:String>
    <sys:String>No</sys:String>
</ComboBox>

where sys is the following xml namespace declaration:

xmlns:sys="clr-namespace:System;assembly=mscorlib"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top