user1896549
user1896549

Reputation: 21

Bind null string to combobox

I'm not sure why this happens At XAML, I have

<ComboBox x:Name="cb" HorizontalAlignment="Left" VerticalAlignment="Top" Width="140" Height="25"/>

At the code behind, I have

cb.ItemsSource = new string[] { null, "Test1", "Test2", "Test3" };

When I load the UI, the combobox has null set. Now if I change it to "Test1", I don't have an option to revert back to null. At the UI, I see "Test1", "Test2" and "Test3". The null string doesn't create a new entry at the combobox. In my case, null is a valid option. If I change null to , it works fine. But I need null to be shown as a valid option. Has anyone see this behavior?

Upvotes: 2

Views: 92

Answers (2)

Angela F
Angela F

Reputation: 79

Instead of binding to a string array, use an object array.

public class DisplayValuePair
    {
        public DisplayValuePair(string d, string v) { this.Display = d; this.Value = v; }
        public string Display { get; set; }
        public string Value { get; set; }
    }

and bind the data as

cb.ItemsSource = new DisplayValuePair[] { 
                new DisplayValuePair("", null), 
                new DisplayValuePair("Test1", "Test1"), 
                new DisplayValuePair( "Test2", "Test2" ), 
                new DisplayValuePair( "Test3", "Test3" ) };

and xaml as

<ComboBox x:Name="cb" HorizontalAlignment="Left" VerticalAlignment="Top" DisplayMemberPath="Display" SelectedValuePath="Value" Width="140" Height="25"/>

So, you don't need to substitute any value at the time of load/save.

Upvotes: 1

Martin
Martin

Reputation: 5623

I normally use a String value like "no selection" for user display instead of null. This avoids the problem you have and is more clearly for the user.

Before sending something to the database I retranslate "no selection" to null.

If I bind to complex items, I also create one representing null.

Usually this "no selection" text is even localized and stored in a resource file, so that it is appropiate for users of different languages.

Upvotes: 1

Related Questions