【发布时间】:2018-12-22 00:01:32
【问题描述】:
我有一个带有Required 属性的自定义Xamarin Forms 组件,我在我的视图模型中将其设置为True。在构造函数中,我调用了一个方法CheckValidity(),它检查是否需要该条目。出于某种原因,Required 显示为 false,直到我输入条目(触发 Text 属性更新)或单击进入或退出条目(触发 Unfocused 事件)。
知道为什么 Required 的初始 True 值在我的组件中发生某些活动之前不会生效吗?谢谢!
在视图中使用
<ui:ValidatingEntry Text="{Binding MyText}" Required="True" />
组件 XAML
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyPackage.ValidatingEntry">
<ContentView.Content>
<StackLayout x:Name="entryContainer">
<Entry x:Name="entry" />
<Label x:Name="message" />
</StackLayout>
</ContentView.Content>
</ContentView>
组件 C#
public partial class ValidatingEntry : ContentView
{
private enum ValidationErrorType
{
NONE,
REQUIRED,
CUSTOM
}
private ValidationErrorType validationErrorType;
public static readonly BindableProperty TextProperty = BindableProperty.Create("Text", typeof(string), typeof(ValidatingEntry), default(string), BindingMode.TwoWay);
public string Text
{
get
{
return (string)GetValue(TextProperty);
}
set
{
SetValue(TextProperty, value);
Debug.WriteLine("set text to: " + value);
CheckValidity();
UpdateMessage();
}
}
public static readonly BindableProperty RequiredProperty = BindableProperty.Create("Required", typeof(bool), typeof(ValidatingEntry), false);
public bool Required
{
get
{
Debug.WriteLine("getting required property: " + (bool)GetValue(RequiredProperty));
return (bool)GetValue(RequiredProperty);
}
set
{
SetValue(RequiredProperty, value);
//THIS NEVER PRINTS
Debug.WriteLine("set required property to: " + value);
CheckValidity();
}
}
public static readonly BindableProperty IsValidProperty = BindableProperty.Create("IsValid", typeof(bool), typeof(ValidatingEntry), true, BindingMode.OneWayToSource);
public bool IsValid
{
get
{
return (bool)GetValue(IsValidProperty);
}
set
{
SetValue(IsValidProperty, value);
}
}
private void CheckValidity()
{
Debug.WriteLine("checking validity");
Debug.WriteLine("required? " + Required); //prints False until Entry is unfocused or user types in Entry
Debug.WriteLine("string empty? " + string.IsNullOrEmpty(Text));
if (Required && string.IsNullOrEmpty(Text))
{
Debug.WriteLine("required but not provided");
IsValid = false;
validationErrorType = ValidationErrorType.REQUIRED;
}
else
{
IsValid = true;
validationErrorType = ValidationErrorType.NONE;
}
}
private void UpdateMessage()
{
switch (validationErrorType)
{
case ValidationErrorType.NONE:
message.Text = "";
break;
case ValidationErrorType.REQUIRED:
message.Text = "This field is required.";
break;
}
}
public ValidatingEntry()
{
InitializeComponent();
entry.SetBinding(Entry.TextProperty, new Binding("Text", source: this));
CheckValidity(); //at this point, Required is always false
entry.Unfocused += (sender, e) =>
{
CheckValidity();
UpdateMessage();
};
}
}
【问题讨论】:
标签: c# xaml xamarin xamarin.forms