2016-04-25 77 views
0
<ComboBox 
    x:Name="comboBox" 
    Margin="281.4,160,259.995,159.958" 
    d:LayoutOverrides="Height" 
    ItemsSource="{Binding _US_STATES}" 
    SelectedIndex="0" 
    SelectedValue="{Binding SelectedState}" 
    SelectedValuePath="{Binding Path=_US_STATES/SHORT}" 
    > 
    <ComboBox.ItemTemplate> 
     <DataTemplate> 
      <Border Padding="2"> 
       <TextBlock Text="{Binding LONG}" /> 
      </Border> 
     </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox> 

以上是我显示的组合框的xaml版本。我可以正确显示它,因为它显示正确的数据。当我尝试获取它被选中的值时,总是RxTracking.model.US_STATES不是它应该的值。wpf组合框SelectedValue获取类名称而不是属性

的US_STATES看起来是这样的:

public class US_STATES : ObservableObject 
{ 
    private string _long; 
    private string _short; 

    public string LONG 
    { 
     get { return _long; } 
     set { Set("LONG", ref _long, value); } 
    } 

    public string SHORT 
    { 
     get { return _short; } 
     set { Set("SHORT", ref _short, value); } 
    } 

    public static ObservableCollection<US_STATES> GetAllStates() 
    { 
     ObservableCollection<US_STATES> ALL = new ObservableCollection<US_STATES> 
     { 
      new US_STATES {LONG="ALABAMA",SHORT="AL" }, 
      new US_STATES {LONG="Alaska", SHORT = "AK"}, 
      new US_STATES {LONG = "Arizona", SHORT = "AZ"}, 
      etc ... 

我收到这是在错误窗口:

System.Windows.Data Error: 40 : BindingExpression path error: 'AL' property not found on 'object' ''US_STATES' (HashCode=8402670)'. BindingExpression:Path=AL; DataItem='US_STATES' (HashCode=8402670); target element is 'ComboBox' (Name='comboBox'); target property is 'NoTarget' (type 'Object') 

System.Windows.Data Error: 40 : BindingExpression path error: 'AL' property not found on 'object' ''US_STATES' (HashCode=15232780)'. BindingExpression:Path=AL; DataItem='US_STATES' (HashCode=15232780); target element is 'ComboBox' (Name='comboBox'); target property is 'NoTarget' (type 'Object') 
+0

[WPF IsEditable = true]的可能重复填充对象的组合框将ToString()显示为选定的项目](https://stackoverflow.com/questions/1844156/wpf-iseditable-true-combobox-filled-with-对象 - 显示最的toString-AS-的) –

回答

1

SelectedValuePath属性是一个字符串。它应该是要用于选定值的列表项类别的属性名称。

如果你想使用的US_STATESSHORT属性,这很简单:

SelectedValuePath="SHORT" 

这就是为什么它哭哭啼啼约'AL' property not found on 'object' ''US_STATES':绑定更新SelectedValuePath_US_STATES/SHORT值(这是“当前项目” ,因为它使用第一个,因为ObservableCollection没有CurrentItem属性 - 即进入CollectionViewSource和ICollectionView,除非您正在对XAML中的东西进行排序或过滤,否则您不必担心这些属性),这是“ AL”。因此,ComboBox尽职地试图找到不存在的US_STATESAL财产。

顺便说一句,你可以抽出自己写一个模板的麻烦,只需设置DisplayMemberPath

DisplayMemberPath="LONG" 
0

您需要设置显示值属性的组合框或在美国类重写的ToString。

发生了什么事情是组合框对存储在其中的对象调用了ToString,并且如果ToString没有被重写,那么它将返回类名称。