我需要知道如何访问我的viewmodel这些行为的IsValid属性。
我宁愿你告诉我一个更强大的行为,因为它们是从头开始制作的,我想用一些已经提升的nuget包进行更强大的验证,尽管它是Xamarin Forms的新手。
这是我的行为,但我无法访问属性“IsValid”我的viewmodel:
public class MesesTrabalhadosValidatorBehavior : Behavior<Entry>
{
private static readonly BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(MesesTrabalhadosValidatorBehavior), false);
public static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty;
public bool IsValid
{
get { return (bool)base.GetValue(IsValidProperty); }
private set { base.SetValue(IsValidPropertyKey, value); }
}
private void bindable_TextChanged(object sender, TextChangedEventArgs e)
{
double result;
double.TryParse(e.NewTextValue, out result);
IsValid = result > 0;
((Entry)sender).TextColor = IsValid ? Color.Green : Color.Red;
}
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += bindable_TextChanged;
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= bindable_TextChanged;
}
}
我的观点:
<Entry Placeholder="Mêses trabalhados" Text="{Binding MesesTrabalhados}" Keyboard="Numeric">
<Entry.Behaviors>
<local:MesesTrabalhadosValidatorBehavior />
</Entry.Behaviors>
</Entry>
<Entry Placeholder="Último salário" Text="{Binding Salario}" Keyboard="Numeric">
<Entry.Behaviors>
<local:SalarioValidatorBehavior />
</Entry.Behaviors>
</Entry>
<ContentView Padding="0,20,0,0">
<Button Text="Calcular" HorizontalOptions="Fill" IsEnabled="{Binding IsValid}" Command="{Binding CalcularFgtsCommand, Mode=TwoWay}"/>
</ContentView>
答案 0 :(得分:2)
您需要添加一个参数,我的偏好是一个命令功能,以便您可以在达到某些条件时调用它。 e.g。
<local:SalarioValidatorBehavior Command="{Binding MyCommandInViewModel}" />
然后是行为中的可绑定属性。
public static readonly BindableProperty CommandProperty = BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(TextChangedBehavior), null);
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
void OnEntryTextChanged(object sender, TextChangedEventArgs args)
{
if (Command != null)
Command.Execute(null);
}
或者您可以在Behavior中使用您的IsValid属性,然后将其绑定回ViewModel中的属性。
<local:SalarioValidatorBehavior IsValid="{Binding IsValid, Mode=TwoWay}" />