列表框不显示数据。列表框出现,但其中没有数据。这是为了复用listbox
对于不同的形式。你能帮忙吗。这只是一个包含一些字符串的列表框。我有
使用 mvvm 模式和 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.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));
}
}
}