2017-10-08 106 views
0

請幫助: 我已經實現了使用Xamarin一個簡單的應用程序的MVVM設計。 我有一個模型(用戶)和一個ViewModel(UserViewModel)。 請注意,這個應用程序是我的第一個Xamarin/MVVM應用程序,我是新手。MVVM INotifyPropertyChanged的工作不

,我有問題的是,添加或刪除用戶,視圖不會更新。 當我添加或刪除用戶時,我可以確認數據庫已更新,但不是我的視圖。

請參閱下面我的代碼,我失去了什麼?

用戶模型:

public class User 
{ 
    public int Id { get; set; } 
    public string Username { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public bool IsActive { get; set; } 

    public List<Role> RolesList { get; set; } 
} 

UserViewModel代碼:

public class UsersViewModel : INotifyPropertyChanged 
     { 
     private UserServices UserServ { get; set; } 

     public User UserSelected { get; set; } 

     private ObservableCollection<User> userList; 
     public ObservableCollection<User> UserList 
     { 
      get 
      { 
       return userList; 
      } 
      set 
      { 
       if (userList != value) 
       { 
        userList = value; 
        NotifyPropertyChanged(); 
       } 
      } 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 

     private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") 
     { 
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
     } 

     public UsersViewModel() 
     { 
      UserServ = new UserServices(); 
      UsersLoadAsync(); 
     } 

     public async void UsersLoadAsync() 
     { 
      UserList = await UserServ.UsersGetAsync(); 
     } 
    } 

用戶助手服務代碼(添加的完整性)

public class UserServices 
    { 

     public async Task<ObservableCollection<User>> UsersGetAsync() 
     { 
      ObservableCollection<User> UserList = await App.UserService.GetAsync(); 

      return UserList; 
     } 

     public async Task<bool> UsersAddAsync(User user) 
     { 
      bool success = await App.UserService.PostAsync(user); 
      return success; 
     } 

     public async Task<bool> UsersRemoveAsync(User user) 
     { 
      bool success = await App.UserService.DeleteAsync(user.Id, user); 
      return success; 
     } 

    } 

查看XAML代碼:

<?xml version="1.0" encoding="utf-8" ?> 
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
      xmlns:local="clr-namespace:PB_Logbook" 
      x:Class="PB_Logbook.MainPage" 
      xmlns:ViewModels="clr-namespace:PB_Logbook.ViewModels;assembly:PB_Logbook"> 

    <ContentPage.BindingContext> 
     <ViewModels:UsersViewModel/> 
    </ContentPage.BindingContext> 
    <StackLayout> 
     <ListView ItemsSource="{Binding UserList, Mode=TwoWay}" HasUnevenRows="True" ItemSelected="Item_SelectedAsync" IsPullToRefreshEnabled="True"> 
     <ListView.ItemTemplate> 
      <DataTemplate> 
       <ViewCell> 
        <StackLayout Orientation="Vertical" Padding="12,6"> 
         <Label Text="{Binding Username}" FontSize="24"/> 
         <Label Text="{Binding FirstName}" FontSize="18" Opacity="0.6"/> 
         <Label Text="{Binding LastName}" FontSize="18" Opacity="0.6"/> 
        </StackLayout> 
       </ViewCell> 
      </DataTemplate> 
     </ListView.ItemTemplate> 
    </ListView> 
    <Button Text="Add" Clicked="AddButton_ClickedAsync"></Button> 
     <Button Text="Remove" Clicked="RemoveButton_ClickedAsync"></Button> 
    </StackLayout> 


</ContentPage> 

查看後面的代碼:

public partial class MainPage : ContentPage 
    { 
     private UserServices UserServices { get; set; } 
     private UsersViewModel UsersVM { get; set; } 


     public MainPage() 
     { 
      InitializeComponent(); 
      UserServices = new UserServices(); 
      UsersVM = new UsersViewModel(); 
     } 

     private async void AddButton_ClickedAsync(object sender, EventArgs e) 
     { 
      await AddUserAsync(); 
     } 

     private async void RemoveButton_ClickedAsync(object sender, EventArgs e) 
     { 
      await RemoveUserAsync(); 
     } 

     private async void Item_SelectedAsync(object sender, EventArgs e) 
     { 
      UsersVM.UserSelected = ((User)((ListView)sender).SelectedItem); 

     } 

     private async void Pull_RefreshAsync(object sender, EventArgs e) 
     { 
      //UsersVM.UsersLoadAsync(); 
     } 

     private async Task AddUserAsync() 
     { 
      Random rnd = new Random(); 
      int rndNumber = rnd.Next(1, 100); 

      User user = new User() 
      { 
       Username = "User " + rndNumber, 
       FirstName = "Firstname " + rndNumber, 
       LastName = "Surname " + rndNumber, 
       IsActive = true 
      }; 

      bool success = await UserServices.UsersAddAsync(user); 

      if (success) 
      { 
       if (!UsersVM.UserList.Contains(user)) 
        UsersVM.UserList.Add(user); 
      } 
     } 

     private async Task RemoveUserAsync() 
     { 
      bool success = await UserServices.UsersRemoveAsync(UsersVM.UserSelected); 

      if (success) 
      { 
       if (UsersVM.UserList.Contains(UsersVM.UserSelected)) 
        UsersVM.UserList.Remove(UsersVM.UserSelected); 
      } 
     } 
    } 

的問題是增加不,我認爲更新/刪除用戶。

謝謝。

+1

替換'名單<>'和'你執行INotifyPropertyChanged'用'的ObservableCollection <>'簡單的天氣應用程序。 – jsanalytics

+0

謝謝你的回覆,@ jstreet。我用ObservableCollection <>替換了List <>,但仍然不起作用。任何其他建議? –

+0

我一有機會就仔細查看。 – jsanalytics

回答

2

如果你是新來Xamarin MVVM,這種聯繫將幫助您瞭解MVVM在Xamarin基礎窗體

https://deanilvincent.github.io/2017/06/03/basic-understanding-of-mvvm-and-databinding-in-xamarin-forms/

我建議爲好,請減輕你的代碼背後,只是實施包括ViewModel中的命令在內的所有內容。

你已經寫了節省當你的代碼工作和更新,但沒有反映看法對嗎?你應該把你的方法放在你保存命令後的列表中。

這樣在您的XAML

<Button Text="Save" Command="{Binding SaveCommand}"/> 

在您的視圖模型,你應該使用命令從Xamarin

public Command SaveCommand{ 
    get{ 
     return new Command(async()=>{ 
      // your command save here 
      // then put your method for fetching the updated list: your UsersLoadAsync(); 
     }); 
    } 
} 

如果你是新來MVVM,你也可以檢查此link。它使用Xamarin MVVM。當你完成,你必須用簡單的MVVM實現

我希望它能幫助你

+0

謝謝你的帖子。我確實遵循了您的建議,並將所有的邏輯和命令移至ViewModel。我也嘗試保存後再次重新加載列表,但它仍不刷新視圖。 –

相關問題