Xamarin 视图不是从构造函数之后的视图模型绑定



我有一个简单的视图,它显示一个标签,其中包含从我的视图模型绑定的问题。 现在,如果我在构造函数中设置属性,我会看到 Label 显示我设置它的任何内容。 如果我从命令函数填充,我没有看到标签已更改。有趣的是,如果我设置 Title 属性(一个具有 get 和 set 的简单字符串),那么无论我在哪里设置它,它都会改变。但由于某种原因,此特定属性不想显示对其的更改。我已经尝试尽可能简化这一点。我尝试在我的 ViewModel 中定义一个公共字符串属性,如果我在构造函数中设置它,那么它就会绑定其他明智的,如果它在我的命令函数中设置,那么它不会改变。

这是我的 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");
    }
}

这是我的观点模型

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;
    }

我没有看到你在哪里为你的MyClassObj属性触发INofityPropertyChanged事件。

而不仅仅是:

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));

是将更改通知视图的人员。

最新更新