Skip to main content
 首页 » 编程设计

c#之ObservableCollection 未绑定(bind)到组合框

2024年02月05日14tuyile006

只是想知道为什么我的 ObservableCollection 没有绑定(bind)到我的组合框 我没有收到任何错误,只是没有填充它。

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

这是我的 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"/> 

我是新手,所以如果我遗漏了一些小东西,我深表歉意。

请您参考如下方法:

显然,您从未创建可以实际绑定(bind)到的 TableList 类的实例。

创建一个带有 TableList 属性的 View 模型类,例如喜欢

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

然后将 MainWindow 的 DataContext 属性设置为 View 模型类的一个实例:

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