如何将ComboBox绑定到ObservableCollection属性?

时间:2016-05-26 20:58:47

标签: c# wpf xaml binding combobox

我想将ObservableCollections的字符串属性绑定到ComboBox。

模型

class Sequence : INotifyPropertyChanged
{
    public Sequence() { }

    private int _id;
    public int ID
    {
        get
        {
            return _id;
        }
        set
        {
            _id = value;
            OnPropertyChanged("ID");
        }
    }
    private string _name;
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }

public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

视图模型:

private ObservableCollection<Sequence> _storedSequences = new ObservableCollection<Sequence>() { };
    public ObservableCollection<Sequence> StoredSequences { get { return _storedSequences; } }

查看XAML:

<ComboBox x:Name="sequencesComboBox" SelectedIndex="0" ItemsSource="{Binding StoredSequences}" DisplayMemberPath="{Binding Name}" >

问题是ComboBox没有显示字符串属性。请参见下图(NQR_GUI_WPF是命名空间):

enter image description here

有人可以告诉我我做错了吗?

3 个答案:

答案 0 :(得分:0)

您需要指定项目的DataTemplate

<ComboBox x:Name="sequencesComboBox" SelectedIndex="0" ItemsSource="{Binding StoredSequences}">
   <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

答案 1 :(得分:0)

除非您需要某些特殊模板,否则无需在ItemTemplate上设置ComboBox。您已绑定到ItemSource,因此要设置显示成员路径,只需为其指定属性的字符串名称:

<ComboBox x:Name="sequencesComboBox" 
          SelectedIndex="0" 
          ItemsSource="{Binding StoredSequences}"
          DisplayMemberPath="Name" >

如果你说它有点尴尬,那么我就不会反对。

答案 2 :(得分:0)

您不需要在DisplayMemberName中绑定。从DisplayMemberPath中删除绑定