C# 每次导航到页面时重新加载数据

C# 每次导航到页面时重新加载数据,c#,xaml,windows-phone-8,C#,Xaml,Windows Phone 8,我有一个Windows Phone页面,通过标准ViewModel作用域加载数据 public Profile() { InitializeComponent(); App.PersonalizedViewModel.favorites.Clear(); DataContext = App.PersonalizedViewModel; this.Loaded += new Routed

我有一个Windows Phone页面,通过标准ViewModel作用域加载数据

public Profile()
        {
            InitializeComponent();
            App.PersonalizedViewModel.favorites.Clear();
            DataContext = App.PersonalizedViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {

            if (!App.PersonalizedViewModel.IsDataLoaded)
            {
                App.PersonalizedViewModel.LoadData();

            }
}
这个很好用。但是,当我从其他页面导航到此页面时,数据仍然是相同的。我的意思是
LoadData()
方法应该重新检查更新的数据,对吗?请建议

编辑:

我的个性化ViewModelClass:

public class PersonalizationViewModel: INotifyPropertyChanged
{
    public PersonalizationViewModel()
    {
        this.favorites = new ObservableCollection<ItemViewModel>();
        this.Bar = new ObservableCollection<Bars>();
    }

    public ObservableCollection<ItemViewModel> favorites { get; private set; }
    public ObservableCollection<Bars> Bar { get; private set; }

    private string _sampleProperty = "Sample Runtime Property Value";

    public string SampleProperty
    {
        get
        {
            return _sampleProperty;
        }
        set
        {
            if (value != _sampleProperty)
            {
                _sampleProperty = value;
                NotifyPropertyChanged("SampleProperty");
            }
        }
    }

    public bool IsDataLoaded
    {
        get;
        private set;
    }

    /// <summary>
    /// Creates and adds a few ItemViewModel objects into the Items collection.
    /// </summary>
    public async void LoadData()
    {
        favorites.Clear();
        try
        {
            var query = ParseObject.GetQuery("Favorite")
                .WhereEqualTo("user", ParseUser.CurrentUser.Username);
            IEnumerable<ParseObject> results = await query.FindAsync();

            this.favorites.Clear();

            foreach (ParseObject result in results)
            {
                string venue = result.Get<string>("venue");
                string address = result.Get<string>("address");
                string likes = result.Get<string>("likes");
                string price = result.Get<string>("price");
                string contact = result.Get<string>("contact");
                this.favorites.Add(new ItemViewModel { LineOne=venue, LineTwo=address, LineThree=likes, Rating="", Hours="", Contact=contact, Price=price, Latitude="", Longitude="" });

            }




            if (favorites.Count == 0)
            {
                //   emailPanorama.DefaultItem = emailPanorama.Items[1];
                MessageBox.Show("You do not have any saved cafes. Long press a cafe in main menu to save it.");

            }
        }
        catch (Exception exc)
        {
            MessageBox.Show("Data could not be fetched!", "Error", MessageBoxButton.OK);

        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
公共类PersonalizationViewModel:INotifyPropertyChanged
{
公共个性化视图模型()
{
this.favorites=新的ObservableCollection();
this.Bar=新的ObservableCollection();
}
公共ObservableCollection收藏夹{get;private set;}
公共可观察集合栏{get;private set;}
私有字符串_sampleProperty=“示例运行时属性值”;
公共字符串SampleProperty
{
得到
{
返回sampleProperty;
}
设置
{
如果(值!=\u sampleProperty)
{
_样本属性=值;
NotifyPropertyChanged(“SampleProperty”);
}
}
}
公共布尔值已加载
{
得到;
私人设置;
}
/// 
///创建一些ItemViewModel对象并将其添加到Items集合中。
/// 
公共异步void LoadData()
{
收藏夹。清除();
尝试
{
var query=ParseObject.GetQuery(“收藏夹”)
.WhereEqualTo(“用户”,ParseUser.CurrentUser.Username);
IEnumerable results=wait query.FindAsync();
this.favorites.Clear();
foreach(ParseObject结果中的结果)
{
字符串地点=result.Get(“地点”);
字符串地址=result.Get(“地址”);
字符串likes=result.Get(“likes”);
字符串price=result.Get(“price”);
string contact=result.Get(“contact”);
this.favorites.Add(新项目视图模型{LineOne=地点,LineTwo=地址,LineThree=喜欢,评级=”,小时=”,联系人=联系人,价格=价格,纬度=”,经度=”});
}
如果(favorites.Count==0)
{
//emailPanorama.DefaultItem=emailPanorama.Items[1];
Show(“您没有任何保存的咖啡馆。长按主菜单中的咖啡馆以保存它。”);
}
}
捕获(异常exc)
{
Show(“无法获取数据!”,“错误”,MessageBoxButton.OK);
}
}
公共事件属性更改事件处理程序属性更改;
私有void NotifyPropertyChanged(字符串propertyName)
{
PropertyChangedEventHandler处理程序=PropertyChanged;
if(null!=处理程序)
{
处理程序(这是新的PropertyChangedEventArgs(propertyName));
}
}
}
个性化视图模型的实现:

protected async override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        await App.PersonalizedViewModel.LoadData();

        user_tb.Text = ParseUser.CurrentUser.Username;


        if (NavigationContext.QueryString.ContainsKey("item"))
        {
            var index = NavigationContext.QueryString["item"];
            var indexParsed = int.Parse(index);
            mypivot.SelectedIndex = indexParsed;
        }

        if (NavigationService.BackStack.Any())
        {
            var length = NavigationService.BackStack.Count() - 1;
            var i = 0;
            while (i < length)
            {
                NavigationService.RemoveBackEntry();
                i++;
            }
        }
    }
受保护的异步覆盖无效OnNavigatedTo(NavigationEventArgs e)
{
基地。导航到(e);
等待App.PersonalizedViewModel.LoadData();
user_tb.Text=ParseUser.CurrentUser.Username;
if(NavigationContext.QueryString.ContainsKey(“项”))
{
var index=NavigationContext.QueryString[“项”];
var indexParsed=int.Parse(索引);
mypivot.SelectedIndex=indexParsed;
}
if(NavigationService.BackStack.Any())
{
var length=NavigationService.BackStack.Count()-1;
var i=0;
while(i
而不是定义此

App.PersonalizedViewModel.favorites.Clear();
DataContext = App.PersonalizedViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
进入
constructor
Profile
我建议将此代码从
constructor
中删除,并将其添加到您的
on navigatedto
中。因此,数据将在
导航后加载

您的OnNavigatedTo方法如下所示

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    App.PersonalizedViewModel.favorites.Clear();
    DataContext = App.PersonalizedViewModel;
    this.Loaded += new RoutedEventHandler(MainPage_Loaded);

}
也许你的问题会解决

编辑 请尝试此查询

 var results = (from find in ParseObject.GetQuery("Favorite").WhereEqualTo("user", ParseUser.CurrentUser.Username) select find);
我试过这个:

var query = from favorite in ParseObject.GetQuery("Favorite")
                            where favorite.Get<string>("user") == ParseUser.CurrentUser.Username
                            select favorite;
                IEnumerable<ParseObject> results = await query.FindAsync();
var query=来自ParseObject.GetQuery(“收藏夹”)中的收藏夹
其中favorite.Get(“用户”)==ParseUser.CurrentUser.Username
选择收藏夹;
IEnumerable results=wait query.FindAsync();

我遇到了一个类似的问题。在这里,您只需生成页面的新实例。您可以通过两种方式来完成此操作。 一种方法是强制使用GUID和页面导航URI,这将创建页面的新实例,并且Load Data()将起作用

      NavigationService.Navigate(new Uri(String.Format("/MainPage.xaml?item={0}", Guid.NewGuid().ToString()), UriKind.RelativeOrAbsolute));

在用户控件中实现该部分页面的第二种方法。如为Load Data()创建用户控件并将其放入构造函数。每次加载页面时,它都会生成一个新实例。

如果前端问题仍然存在,可以尝试此方法

1.您是否在xaml页面中提到了以下属性

 <UserControl Loaded="MainPage_Loaded">

因此,每次页面加载时,数据都会加载到页面上

2.如果代码隐藏中没有问题,那么数据必须存在,因为它是WPF应用程序而不是网页


希望你觉得它有用。

我看不出有什么问题,但是,我认为你需要缩小这个问题的范围

首先,您从两个位置调用LoadData。1个从主页加载,1个从OnNavigatedTo。在MainPage_Load中,它是有条件的,在OnNavigatedTo中,它总是被调用。我建议您通过代码获得一条路径,而不是2条路径,这样您就不会获得不同的体验。我个人建议(在不知道所有细节的情况下)从OnNavigatedTo调用load data,而不是MainPage_load。如果您希望有条件地执行此操作,那么这很好,但是如果您是从内存加载数据,那么这确实是不必要的,因为只有几毫秒的时间才能提高性能。另外,如果您不是从内存加载,您可能不希望有条件地加载它,因为底层的
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
   base.OnNavigatedTo(e);

   App.PersonalizedViewModel.favorites.Clear();
   DataContext = App.PersonalizedViewModel;
   // this.Loaded += new RoutedEventHandler(MainPage_Loaded);

   if (!App.PersonalizedViewModel.IsDataLoaded)
   {
       App.PersonalizedViewModel.LoadData();
   }
}