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

标签 c# .net wpf xaml

只是想知道为什么我的 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();
}

关于c# - ObservableCollection 未绑定(bind)到组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39387325/

相关文章:

c# - 在类中添加不在接口(interface)定义中的公共(public)方法是一个好习惯吗?我什么时候应该这样做?

c# - Windows Phone 文本框以只读模式显示插入符

c# - 修复 C# .NET 中由 ILMerge 引起的类型冲突

wpf - RadTabControl 在 swiching tabitems 中重新加载内容

c# - 了解线程以及与 .NET 和 WPF 的同步

c# - 如何创建从实现接口(interface)的基类派生的实例列表?

c# - 非泛型类型 'ActionResult' 不能与类型参数一起使用

.net - 如何在桌面 .NET 应用程序中存储数据?

C#类库项目依赖注入(inject)bootstrap

c# - MVVM 混合行为和 RelayCommand 未按预期工作