2010-06-18 60 views
2

这是我没有得到的东西。如果我有一个例如一个profile.xaml页面,我有一个ProfileViewModel用户实例。如何通过User属性告诉ProfileViewModel以用户名加载我想要的ID?将特定ID传递给MVVM

我的意思是:当我点击另一页中的按钮打开该页面时,如何将用户标识传递到profileviewmodel?

对于实例

Userlist.xaml有一个用户列表。点击一下,并加载Profile.Xaml的一个实例,但是如何将userId传递给viewmodel?我不需要profile.xaml中的一些依赖属性,然后传递它?

请告诉我,如果这对你有意义:)

回答

2

您应该考虑将Userlist.xaml中的用户列表绑定到ProfileViewModel实例的集合,然后您可以将特定的ProfileViewModel提供给profile.xaml。

在这个例子中,你Userlist.xaml将包括:

<UserControl Name="userView"> 
    <!-- other stuff --> 
    <ItemsControl ItemsSource={Binding Users}> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal"> 
        <TextBlock Text="{Binding UserName}" /> 
        <Button Content="View User Profile" 
        Command="{Binding ElementName=userView, Path=DataContext.ViewUserProfileCommand}" 
        CommandParameter="{Binding}" /> 
       </StackPanel> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 
    <!-- other stuff --> 
</UserControl> 

和你UserlistViewModel将包括:

#region Users Property 

    public const string UsersPropertyName = "Users"; 

    private ObservableCollection<IProfileViewModelViewModel> _users; 

    public ObservableCollection<IProfileViewModelViewModel> Users 
    { 
     get { return _users; } 
     set 
     { 
      if (_users == value) 
       return; 

      _users = value; 
      RaisePropertyChanged(UsersPropertyName); 
     } 
    } 

    #endregion 

    public RelayCommand<IProfileViewModel> ViewUserProfileCommand 
     = new RelayCommand<IProfileViewModel>(ViewUserProfileCommandExecute); 

    private void ViewUserProfileCommandExecute(IUserProfileViewModel userProfileViewModel) 
    { 
     // display your profile view here 
    } 

芦苇上面提到的,用户配置文件的视图模型传递到一个方法您的其他页面将是MVVM Light Toolkit's messaging

2

有多种选择,在这里。

如果您使用的是“父级”ViewModel,则可以使用特定的用户ID构建一个新的ProfileViewModel,并将其设置为直接由您的View拾取的属性。这是我在我的MVVM article中使用的方法。或者,如果您有一个ProfileViewModel(和ProfileView),并且它没有“连接”到您直接选择用户的屏幕/视图,那么最佳选择通常是使用某种形式的消息传递服务。这是MVVM Light使用的方法。