2015-11-19 74 views
2

我不知道为什么会这样 在XAML,我有绑定空字符串组合框

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

在后面的代码,我有

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

当我加载UI时,组合框具有空集。现在,如果我将它更改为“Test1”,我没有选项可以恢复为空。在UI中,我看到“Test1”,“Test2”和“Test3”。空字符串不会在组合框中创建新条目。就我而言,null是一个有效的选项。如果我将null更改为,它工作正常。但我需要将null显示为有效的选项。 有没有人看到这种行为?

回答

1

不是绑定到字符串数组,而是使用对象数组。

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; } 
    } 

,并绑定数据

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

和XAML作为

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

所以,你并不需要在加载的时间来替换任何值/保存。

+0

我喜欢这个解决方案。这个类甚至可以是通用的,即将“Value”属性的类型更改为泛型类型,以便您可以使用它来显示各种对象的字符串。 – Martin

+0

是的..这是一个好主意!更通用! –

1

我通常使用字符串值,如“无选择”用于用户显示而不是空值。 这样可以避免您遇到的问题,并且更清楚地为用户提供帮助。

在将某些内容发送到数据库之前,我将“no selection”重新设置为null。

如果我绑定到复杂项目,我也创建一个代表null。

通常这个“无选择”文本甚至本地化并存储在一个资源文件中,以便适用于不同语言的用户。

+0

非常感谢马丁。现在,我会使用这个选项,虽然我需要在加载和保存时替换值。直到我找到更好的方式,我才能使用这个黑客。 – user1896549

+0

我找到了更好的方法,请在这里发帖:-) – Martin