为什么我的 Listview ItemsSource 为空(uwp app c#)

why is my Listview ItemsSource null (uwp app c#)

我正在尝试将我的 ViewModel 中的列表绑定到我的页面中的 ListView,但我无法让它工作,尽管列表中填充了值,但 ItemsSource 始终为 null。

我就是这样设置的。

这些属性已添加到我的页面标签中 xaml

xmlns:viewmodels ="using:TimeMachine3.ViewModels"
d:DataContext="{d:DesignInstance viewmodels:MasterViewModel}"

我的 LisstView 定义为

<ListView x:Name="lstMainMaster" ItemsSource="{Binding MyList}" SelectionChanged="lstMainMaster_SelectionChanged">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{x:Bind Name}"/>
                    <TextBlock Text="{x:Bind Number}"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

在我的master.cs(页面代码)中我有

    private ViewModels.MasterViewModel viewmodel;

    //constructor
    public master()
    {
        this.InitializeComponent();
        this.Loaded += Master_Loaded;
    }

    private void Master_Loaded(object sender, RoutedEventArgs e)
    {
        viewmodel = new ViewModels.MasterViewModel();
        viewmodel.populate();
    }

在 masterViewmodel(页面的视图模型)中我有这段代码

    private ObservableCollection<Month> _myList;
    public ObservableCollection<Month> MyList{ get {return _myList; } }

    public void Populate()
    {
        _myList = new ObservableCollection<Month>(DataBase.GetMonths(2017));
    }

它为空,因为您在加载视图后更改了 MyList 指向的引用,并且没有通知视图更改(通过 INotifyPropertyChanged)。因此,视图不知道它需要刷新绑定。

public void Populate()
{
    _myList = new ObservableCollection<Month>(DataBase.GetMonths(2017));
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MyList)));
}

或同等学历。

我刚刚意识到,如果我的 DataContext 设置正确,我不必实现 InotifyChanged 接口。

我更改了数据上下文的设置方式

xmlns:viewmodels ="using:TimeMachine3.ViewModels"
enter code here`d:DataContext="{d:DesignInstance viewmodels:MasterViewModel}"

<Page
...
xmlns:viewmodels ="using:TimeMachine3.ViewModels"
.../>
<Page.DataContext>
   <viewmodels:MasterViewModel>
</Page.DataContext>

现在,itemssource 将在调用 InitializeComponent() 后立即设置,如果我的列表被更改,那么我的 ListView 将更新而无需添加更多代码(我什至不必实现 INotifyChanged)