2017-01-19 95 views
1

我有一個簡單的視圖,顯示一個標籤與正在從我的ViewModel綁定的問題。現在如果我在構造函數中設置屬性,我會看到標籤顯示我設置的任何內容。如果我從我的命令函數填充,我看不到標籤更改。有趣的是,如果我設置Title屬性(一個簡單的字符串有一個get和set),那麼無論我設置它在哪裏都會改變。但由於某些原因,此特定屬性並不想顯示其更改。我儘可能地簡化了這一點。我試圖在我的ViewModel中定義一個公共字符串屬性,如果我在構造函數中設置它,而不是在綁定其他方面,如果它在我的命令函數中設置,那麼它不會改變。Xamarin查看未綁定從視圖模型構造函數後

這裏是我的XAML

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
     x:Class="Pre.MyPage" 
     Title="{Binding Title}" 
     Icon="about.png"> 
<StackLayout VerticalOptions="Center" HorizontalOptions="Center" > 
    <Label Text="{Binding MyClassObj.Question, Mode=TwoWay}"/> 
</StackLayout> 
</ContentPage> 

這裏是我的背後

public partial class MyPage : ContentPage 
{ 
    MyViewModel vm; 
    MyViewModel ViewModel => vm ?? (vm = BindingContext as MyViewModel); 
    public MyPage() 
    { 
     InitializeComponent(); 
     BindingContext = new MyViewModel(Navigation); 
    } 
    protected override void OnAppearing() 
    { 
     base.OnAppearing(); 
     ViewModel.LoadQuestionCommand.Execute("1"); 
    } 
} 

下面的代碼是我的ViewModel

public class MyViewModel : ViewModelBase 
{ 
    public MyClass MyClassObj {get;set;} 

    ICommand loadQuestionCommand; 
    public ICommand LoadQuestionCommand => 
     loadQuestionCommand ?? (loadQuestionCommand = new Command<string>(async (f) => await LoadQuestion(f))); 

    public MyViewModel(INavigation navigation) : base(navigation) 
    { 
     Title = "My Title";    
    } 
    async Task<bool> LoadQuestion(string id) 
    { 
     if (IsBusy) 
      return false; 
     try 
     { 
      IsBusy = true; 

      MyClassObj = await StoreManager.QuestionStore.GetQuestionById(id); 
      //MyClassObject is populated when I break here 
     } 
     catch (Exception ex) 
     { 
      Debug.WriteLine(ex.Message); 
     } 
     finally 
     { 
      IsBusy = false; 
     } 
     return true; 
    } 

回答

1

我沒有看到你在放INofityPropertyChanged事件爲您的MyClassObj屬性。

而不只是:

public MyClass MyClassObj {get;set;} 

你應該是這樣的:

MyClass myClassObj; 
public MyClass MyClassObj 
{ 
    get {return myClassObj;} 
    set 
    { 
     //if they are the same you should not fire the event. 
     //but since it's a custom object you will need to override the Equals 
     // of course you could remove this validation. 
     if(myClassObj.Equals(value)) 
      return; 

     myClassObj = value; 

     //This method or something has to be in your VieModelBase, similar. 
     NotifyPropertyChanged(nameof(MyClassObj)); 
    } 
}  

當最後一個方法

NotifyPropertyChanged(nameof(MyClassObj)); 

是誰通知有關更改的視圖。