每当页面导航到

时间:2015-05-04 18:24:05

标签: mvvm data-binding windows-phone-8.1

我在我的项目中使用MVVM light和Cimbalino Toolkit,我希望在页面导航到时更新我的​​ListView。 我在View Model中实现了一个异步方法:

private async void getMyNoteList()
     {
         ObservableCollection<Note> list = await _noteSessionService.getNoteList();
         NoteList = new ObservableCollection<Note>(list);        
     }

这里,在我的NoteListPageViewModel.cs中。我有一个属性NoteList:

public ObservableCollection<Note> NoteList
    {
        get { return _noteList; }

        set { Set(() => NoteList, ref _noteList, value); }
    }

它与页面中的ListView有关。

<ListView  x:Name="NoteListView" ItemsSource="{Binding NoteList}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Border 
                    BorderBrush="White"
                    BorderThickness="2"
                    CornerRadius="5"
                    Width="360"
                    Margin="10,5">

                    <FlyoutBase.AttachedFlyout>
                        <MenuFlyout>
                            <MenuFlyoutItem Text="Delete"  
                        />

                            <MenuFlyoutItem Text="Edit" 
                         />
                        </MenuFlyout>
                    </FlyoutBase.AttachedFlyout>

                    <StackPanel >
                        <TextBlock
                               FontSize="30" Text="{Binding NoteTitle}"/>
                        <TextBlock
                               FontSize="25"
                               TextWrapping="Wrap" Text="{Binding NoteContent}"/>
                    </StackPanel>

                </Border>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

由于其他服务添加/删除了注释列表,因此每次导航到页面时都需要调用异步方法,以便最新更新列表。

我把getMyNoteList()放在这里:

 public NoteListPageViewModel(INavigationService navigationService,
        INoteSessionService noteSessionService,
        IMessageBoxService messageBox,
        ILogManager logManager)
    {
        _navigationService = navigationService;
        _noteSessionService = noteSessionService;
        _messageBox = messageBox;
        _logManager = logManager;
        getMyNoteList();

        DeleteComamand = new RelayCommand(
           () =>
           {


           });

        EditCommand = new RelayCommand(
           () =>
           {

           });

    }

并且页面只能在第一次导航到时更新。

由于我使用的是GalaSoft.MvvmLight,在viewModelLocator中,我已经注册了ViewModel:

SimpleIoc.Default.Register<NoteListPageViewModel>();

是否有任何解决方案可以满足我的期望?在默认的相关Page.xaml.cs中,我不做任何事情:

 protected override void OnNavigatedTo(NavigationEventArgs e)
    {


    }

1 个答案:

答案 0 :(得分:1)

最好的方法是使用MVVM Light消息。 因此,在页面的OnNavigatedTo方法中,只需发送带有一些字符串值的NotificationMessage,以指示页面已导航到。

在NotificationMessage的viewmodel注册表中,使用Async方法对其进行重新加载列表。

如果您不了解MVVM Light的消息传递系统 - 请查看MSDN杂志网站上的深入教程https://msdn.microsoft.com/en-us/magazine/dn745866.aspx