![](/img/trans.png)
[英]Correct approach to make a ListBox Page Navigation using MVVM on Windows Phone
[英]ListBox Navigation Page MVVM Light in Windows Phone
我正在构建基于位置的服务Windows Phone应用程序,这是我的第一个应用程序。 我在使用MVVM Light进行页面导航时遇到困难。 我正在遵循Jesse Liberty教程 ,到目前为止,当我单击FirstPage上的ListBox上的项目时,它可以导航到SecondPage。
我想做的是,用户从FirstPage
ListBox
中选择的内容与SecondPage
ListPicker
绑定。 因此,用户可以轻松地更改要从SecondPage
搜索的内容。
MainPage.xaml
<ListBox x:Name="MainMenu" ItemTemplate="{StaticResource MainMenu}" ItemsSource="{Binding Categories}" Margin="0,97,0,0">
<Custom:Interaction.Triggers>
<Custom:EventTrigger EventName="SelectionChanged">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding MainMenuCommand, Mode=OneWay}"/>
</Custom:EventTrigger>
</Custom:Interaction.Triggers>
</ListBox>
MainPage.xaml.cs
public MainPage()
{
InitializeComponent();
Messenger.Default.Register<CategoryModel>(this,c => NavigationService.Navigate(new Uri("/Views/VenueList.xaml", UriKind.Relative)));
}
MainViewModel.cs
public MainViewModel()
{
MainMenuCommand = new RelayCommand<CategoryModel>((msg) => GoToVenueList(msg));
}
public RelayCommand<CategoryModel> MainMenuCommand
{
get;
private set;
}
private void GoToVenueList(CategoryModel msg)
{
Messenger.Default.Send(msg);
}
private CategoryModel _selectedItem;
public CategoryModel SelectedItem
{
get { return _selectedItem; }
set
{
if (_selectedItem == value)
{
return;
}
var oldValue = _selectedItem;
_selectedItem = value;
RaisePropertyChanged("SelectedItem", oldValue, value, true);
}
}
VenueList.xaml
<toolkit:ListPicker Margin="0,153,0,0" Background="{StaticResource PhoneAccentBrush}" VerticalAlignment="Top"
SelectedItem="{Binding Item, Mode=TwoWay}"
ItemsSource="{Binding Categories}"
ItemTemplate="{StaticResource CategorySelector}" FullModeHeader="Category" FullModeItemTemplate="{StaticResource FullCategorySelector}" BorderBrush="{StaticResource PhoneAccentBrush}" />
希望任何人都能帮助我解决问题。
VenueListViewModel
public VenueListViewModel()
{
Messenger.Default.Register<PropertyChangedMessage<CategoryModel>>(
this,
(action) => Item = action.NewValue
);
}
private CategoryModel _item;
public CategoryModel Item
{
get
{
return _item;
}
set
{
if (_item == value)
{
return;
}
_item = value;
// Update bindings, no broadcast
RaisePropertyChanged("Item");
}
}
这是典型的情况,您需要两个ViewModel相互通信。
在这种情况下,最好的方法是使用框架的Messaging
功能,尤其是因为使用mvvm-light
。
如果您在这方面需要帮助,可以在网上找到很多示例和文档(例如,在channel9上查找Laurent Bugnion的网络广播,例如, 该视频 ),实际上只是为某种类型的回调注册回调的问题。邮件,然后从其他地方发送。
这样,您的第一个视图模型就会向第二个视图模型发送一条消息,说明已选择了哪个列表项。 您的目标视图模型会自动更新以反映这一点。 然后,您的初始viewmodel命令导航到目标页面,并且由于它使用了目标视图模型,因此效果很好。
有几种可能性,我主要使用列表框的SelectedItem解决方案...但是纯消息传递也是可能的。
使用堆栈溢出查看解决方案中的类似问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.