2010-06-18 59 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使用的方法。