【发布时间】:2017-08-28 08:50:44
【问题描述】:
我是 Xamarin 的新手,我正在使用 ActivityIndicator 告诉用户该应用正在下载数据。问题是我正在使用 MVVM 模式,我需要从 ViewModel 设置值 IsRunning 和 IsVisible。我的观点很简单:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:HmtMobile"
x:Class="HmtMobile.MainPage"
Title="Přihlášení"
>
<ScrollView>
<StackLayout Margin="10" Spacing="15" VerticalOptions="Center">
<ActivityIndicator x:Name="ActivityIndicator" Color="Green" IsRunning="{Binding IsBusy, Mode=TwoWay}" IsVisible="{Binding IsBusy, Mode=TwoWay}"/>
<Entry Placeholder="Uživatelské jméno" Text="{Binding UserName}"></Entry>
<Entry Placeholder="Heslo" Text="{Binding Password}" IsPassword="True"></Entry>
<Button Text="Přihlášení" Command="{Binding LoginCommand}" BackgroundColor="#77D065" TextColor="White"></Button>
</StackLayout>
</ScrollView>
在视图构造函数中,我分配了BindingContext
public MainPage()
{
InitializeComponent();
this.BindingContext = new CredentialViewModel(this);
}
其他属性有效,因为当我想登录时,属性返回实际的用户名和密码,但双向绑定没有。属性被声明为相同,所以我不明白为什么会这样。
private string password;
public string Password
{
get { return password; }
set { password = value; OnPropertyChanged(); }
}
private bool isBusy;
public bool IsBusy
{
get { return isBusy; }
set { isBusy = value; OnPropertyChanged(); }
}
我正在使用简单的登录方法。
private async Task Login()
{
IsBusy = true;
await Task.Delay(5000);
}
ActivityIndicator 没有出现。有谁知道为什么? OnPropertyCHanged 是这样编码的:
public class Bindable
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
【问题讨论】:
-
为什么必须是 TwoWay?对于您正在做的事情,默认(OneWay)就足够了。尝试删除 TwoWay 声明,看看它是否有效。
-
你确定吗?我需要在 VM 中设置值并填充它以在我尝试将其更改为 OneWay 时对其进行查看,但它无法识别代码中的更改。
-
OneWay表示当您从BindingContext设置它时,它应该在 UI 中相应更新。如果未正确更新,则您的NotifyPropertyChanged机制可能有问题。 -
OnPropertyChanged 的编码方式与我在问题更新中显示的方式相同。
-
您的 ViewModel 中是否定义了
INotifyProeprtyChanged?不知道为什么它在一个叫做 Bindable 的类中......或者你的 ViewModel 是从那个派生的?简单地这样做:public class CredentialViewModel : INotifyPropertyChanged
标签: c# xamarin mvvm data-binding xamarin.forms