2

I have a combobox with which I'm adding in a <x:Null/> at the beginning, as 'null' is a perfectly valid value for the bound property, but WPF doesn't seem willing to set it. Here's the XAML:

<ComboBox SelectedItem="{Binding PropertyName}">
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <x:Null/>
            <CollectionContainer Collection="{Binding (available items)}"/>
        </CompositeCollection>
    </ComboBox.ItemsSource>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name, FallbackValue='(None)'}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

The collection in (available items) has objects with a Name property. The combobox correctly displays (None) when the current value of PropertyName is null, and it sets to an item in the collection when I selected one, but when I select (None), it doesn't set the property to null. Is there any way I can make it do this?

Flynn1179
  • 11,925
  • 6
  • 38
  • 74
  • I can't admit, that if `PropertyName` is `null`, then selected value in combobox is `(None)`. I have `(None)` entry in dropdown list, but it's not selected. – Rekshino Oct 23 '18 at 14:31
  • Possible duplicate of [Why can't I select a null value in a ComboBox?](https://stackoverflow.com/questions/518579/why-cant-i-select-a-null-value-in-a-combobox) – Rekshino Oct 24 '18 at 07:14

2 Answers2

1

Replace <x:Null> with an actual instance of something and use a converter:

public class Converter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => value;

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
        value is short ? null : value;
}

XAML:

<ComboBox>
    <ComboBox.SelectedItem>
        <Binding Path="PropertyName">
            <Binding.Converter>
                <local:Converter />
            </Binding.Converter>
        </Binding>
    </ComboBox.SelectedItem>
    <ComboBox.ItemsSource>
        <CompositeCollection xmlns:sys="clr-namespace:System;assembly=mscorlib">
            <sys:Int16 />
            <CollectionContainer Collection="{Binding Source={StaticResource items}}"/>
        </CompositeCollection>
    </ComboBox.ItemsSource>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name, FallbackValue='(None)'}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
mm8
  • 163,881
  • 10
  • 57
  • 88
0

I recently ran into this... One way to approach this is to have a view model that can expose a null value property:

public class ListItemValue<T>
{
   public ListItemValue(string name, T value)
   {
      Name = name;
      Value = value;
   }

   public string Name { get; }

   public T Value { get; }
}
RQDQ
  • 15,461
  • 2
  • 32
  • 59