【发布时间】:2017-01-19 04:58:38
【问题描述】:
我有一个简单的视图,它显示一个带有问题的标签,该问题是从我的 ViewModel 绑定的。现在,如果我在构造函数中设置属性,我会看到标签显示我设置的任何内容。如果我从我的命令函数中填充,我看不到标签已更改。有趣的是,如果我设置 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;
}
【问题讨论】: