简体   繁体   English

MVVM模式中的WPF DataBinding ListBox

[英]WPF DataBinding ListBox in MVVM Pattern

I am databind Listbox in MVVM pattern,I am using Entity Framework for getting data,this is how I am doing 我正在以MVVM模式进行数据绑定列表框,我正在使用实体框架获取数据,这就是我正在做的

XAML: XAML:

<ListBox Margin="0,26,860,-146" x:Name="lstuser" ItemsSource="{Binding ListBoxDS}"/>

C# code: C#代码:

private ObservableCollection<Users> _lstusers;
public ObservableCollection<Users> ListBoxDS
{
    get
    {
        if (_lstusers == null)
        {
            _lstusers = new ObservableCollection<Users>();
        }
        return _lstusers;
    }
    set
    {
        _lstusers = value;
        NotifyOfPropertyChange("ListBoxDS");
    }
}


public class Users
{
    public int UserID { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
}      

DataContext: 的DataContext:

public static IList<Users> GetAllUsers
{
    try
    {
        using (var context = new ApplicationContext())               
        {
            return context.UsersInfo.ToList();
        }
    }
    finally
    {

    }
}

and in my ViewModel 在我的ViewModel中

var allusersList=GetAllUsers();
     var users = allusersList.Where(a => a.FirstName =="some value").ToList();
                        foreach (var item in users)
                        {
                            _lstusers.Add(new Users { UserID = item.Id, UserName = item.Username,FirstName=item.firstname });
                        }

When I am ruuning my project,its not showing any item in Listbox, I am following this link I have debugged it, data is appearing in ListDS. 当我查看我的项目时,它没有在列表框中显示任何项目,我正在调试该链接 ,所以数据显示在ListDS中。

in your code i cant see that you add the item to your list. 在您的代码中,我看不到您将项目添加到列表中。 it should be 它应该是

var users = allusersList.Where(a => a.FirstName =="some value").ToList();
foreach (var item in users)
{
      ListBoxDS.Add(new Users { UserID = item.Id, UserName = item.Username,FirstName=item.firstname });
 }

EDIT: then your code should work if you set the right DataContext. 编辑:然后,如果您设置正确的DataContext,您的代码应该可以工作。 you can check this with Snoop at runtime. 您可以在运行时使用Snoop进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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