列表框未显示 mvvm wpf 中的数据

问题描述 投票:0回答:1

列表框不显示数据。列表框出现,但其中没有数据。这是为了复用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();
     
     
 }
}
c# .net wpf mvvm listbox
1个回答
0
投票

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));
    }
   }


   }
© www.soinside.com 2019 - 2024. All rights reserved.