简体   繁体   中英

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

XAML:

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

C# code:

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:

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

    }
}

and in my 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.

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. you can check this with Snoop at runtime.

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