Listbox not showing data in mvvm wpf

58 Views Asked by At

Listbox not displaying data. Listbox is appearing but no data in it. This is to reuse listbox
for different forms. Could you help. This is just a listbox with some strings in it. I have
implemented it with mvvm pattern and wpf.

Mainwindow.xaml:

  <Window.DataContext>
    <local:Listboxviewmodel/>
</Window.DataContext>

<Grid>
    <ListBox Width="100" Height="100" ItemsSource="{Binding Items,    
     Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"  SelectedItem="{Binding SelectedItem,     
     Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
    </ListBox>

</Grid>
</Window>

mainwindow.xaml.cs:
 public partial class MainWindow : Window
 {
 public MainWindow()
 {
     var model = new Listboxviewmodel();
     model.Items.Add("orange");
     model.Items.Add("apple");
     model.Items.Add("grapes");
     InitializeComponent();
     this.DataContext = new Listboxviewmodel();
     
     
 }
}

Listboxviewmodel is provided in the answer section.


listboxviewmodel.cs:

namespace WpfApp2
{
public class Listboxviewmodel:INotifyPropertyChanged
{
    private ObservableCollection<string> _items = new ObservableCollection<string>();
    private ObservableCollection<string> _selectedItem;

    public ObservableCollection<string> Items
    {
        get
        {
            return _items;
        }
        set
        {
            _items = value;
            SetPropertyChanged("Items");
        }
    }
    public ObservableCollection<string> SelectedItem
    {
        get
        {
            return _selectedItem;
        }
        set
        {
            _selectedItem = value;
            SetPropertyChanged("SelectedItem");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void SetPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null) PropertyChanged(this, new    PropertyChangedEventArgs(propertyName));
    }
   }


   }
2

There are 2 best solutions below

2
mm8 On

Set the DataContext to the instance that you are adding items to:

public MainWindow()
{
    var model = new Listboxviewmodel();
    model.Items.Add("orange");
    model.Items.Add("apple");
    model.Items.Add("grapes");
    InitializeComponent();
    this.DataContext = model; // <--
}

And there is no reason to set the DataContext in the XAML markup when you set it programmatically. Remove this:

<Window.DataContext>
    <local:Listboxviewmodel/>
</Window.DataContext>
0
Divya rajasekhar On

this.DataContext = new Listboxviewmodel();

  • The issue is here. You have populated a Listboxviewmodel named model , But while assigning DataContext , you are creating a new Listboxviewmodel.

Could you try assigning the model to the DataContext.