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));
}
}
}
Set the
DataContextto the instance that you are adding items to:And there is no reason to set the
DataContextin the XAML markup when you set it programmatically. Remove this: