简体   繁体   中英

ObservableCollection not binding to combo box

Just wondering as to why my ObservableCollection is not binding to my Combo Box I don't get any errors it just doesn't populate it.

public class TableList : ObservableCollection<TableName>
{
    public TableList() : base()
    {
        Add(new TableName(1, "Notes"));
        Add(new TableName(2, "TemplateNotes"));
    }
}

public class TableName
{
    private int noteID;
    private string noteName;

    public TableName(int ID, string name)
    {
        this.noteID = ID;
        this.noteName = name;
    }

    public int NoteID
    {
        get { return noteID; }
        set { noteID = value; }
    }

    public string NoteName
    {
        get { return noteName; }
        set { noteName = value; }
    }
}

This is my XAML

<ComboBox 
    x:Name="noteSaveToSelection" 
    HorizontalAlignment="Left" 
    Height="35" 
    Margin="155,932,0,0" 
    VerticalAlignment="Top" 
    Width="180" 
    ItemsSource="{Binding TableList}" 
    DisplayMemberPath="NoteName" 
    SelectedValuePath="NoteID"/>

I am new to this so i apologise if i have missed something small.

Apparently you never create an instance of your TableList class that you can actually bind to.

Create a view model class with a TableList property, eg like

public class ViewModel
{
    public TableList TableList { get; } = new TableList();
}

Then set the DataContext property of your MainWindow to an instance of the view model class:

public MainWindow()
{
    InitializeComponent();
    DataContext = new ViewModel();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM