具有可绑定自定义对象的自定义viewcell

时间:2017-12-15 06:34:13

标签: c# xamarin mvvm xamarin.forms model-binding

我在这里遇到了一个困扰我的问题,过去几天我无法找到明确的解释。我想要完成的事情: 创建一个自定义ViewCell,其中BindableProperty是一个复杂对象。 这一刻我在BindableProperty中收到一个空值。 任何提示都有很大的帮助。

这是我的ViewCell的Code-Behind:。

public partial class ValidatableText : ViewCell
{
    public static readonly BindableProperty BindedObjectProperty =
        BindableProperty.Create(
            nameof(ObjectToValidate),
            typeof(ValidatableObject<string>),
            typeof(ValidatableText),
            default(ValidatableObject<string>));


    public ValidatableObject<string> ObjectToValidate
    {
        get
        {
            var value = GetValue(BindedObjectProperty);
            var result = value as ValidatableObject<string>;
            return result;
        }
        set
        {
            SetValue(BindedObjectProperty, value);
            OnPropertyChanged(nameof(ObjectToValidate));
        }
    }

    protected override void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        if (!string.IsNullOrWhiteSpace(propertyName) && propertyName == BindedObjectProperty.PropertyName)
        {
            base.OnPropertyChanged(propertyName);
        }
    }

    public ICommand ValidateInput
    {
        get
        {
            return new Command(() =>
            {
                this.ObjectToValidate.Validate();
            });
        }
    }

    public ValidatableText()
    {
        InitializeComponent();
        BindingContext = this;
    }
}

这样称呼:

<ContentPage.Content>
    <TableView Intent="Form" HasUnevenRows="True">
        <TableRoot >
            <TableSection Title="Creditentials">
                <cells:ValidatableText  ObjectToValidate="{Binding Email}">
                </cells:ValidatableText>
            </TableSection>
        </TableRoot>
    </TableView>
</ContentPage.Content>

来电者的ViewModel:

    public ValidatableObject<string> Email
    {
        get => _email;
        set
        {
            _email = value;
            this.OnPropertyChanged();
        }
    }        

     public RegisterUserViewModel()
     {
        this.Email = new ValidatableObject<string>();

        this.Email.Validations.Add(new EmailRule<string>(){ValidationMessage = "Invalid email format"});
     }

最好的问候。

0 个答案:

没有答案