MVVMCross中的EditText编辑功能

问题描述 投票:2回答:2

我想知道如何才能在EditTextmvvmcross中启用和禁用编辑功能。

<EditText
   style="@style/InputNumbersEditText"
   android:layout_weight="1"
   android:layout_width="0dp"
   android:focusable="true"
   android:layout_height="wrap_content"
   android:inputType="numberDecimal|numberSigned"
   local:MvxBind="Text Age" />
c# xml xamarin mvvmcross
2个回答
5
投票

由于android:editable="false"deprecated,你应该设置android:inputType="none"来禁用EditText上的输入。如果你想将inputTypeEditText与MvvmCross绑定,你可以创建一个Value Converter,它从ViewModel获取一个输入值,并返回Android.Text.InputTypes类型的答案。

示例实现:

在您的Android项目中添加一个类,其中包含以下内容:

public class EditTextEnabledValueConverter : MvxValueConverter<bool, InputTypes>
{
    protected override InputTypes Convert(bool value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value)
            return InputTypes.ClassNumber | InputTypes.NumberFlagDecimal | InputTypes.NumberFlagSigned;

        return InputTypes.Null;
    }
}

并在您的布局文件中:

<EditText
   style="@style/InputNumbersEditText"
   android:layout_weight="1"
   android:layout_width="0dp"
   android:focusable="true"
   android:layout_height="wrap_content"
   local:MvxBind="Text Age; InputType EditTextEnabled(MyProperty)" />

其中MyProperty是ViewModel上的可绑定布尔值。您可以使用任何类型作为源类型,它不必是布尔值。快乐转换!


1
投票

我用其他方式解决了我的问题。创建自定义绑定绑定到View的Enabled属性。

自定义绑定的代码

public class ViewEnabledTargetBinding : MvxPropertyInfoTargetBinding<View>
{
    // used to figure out whether a subscription to MyPropertyChanged       

    public override MvxBindingMode DefaultMode => MvxBindingMode.TwoWay;

    public ViewEnabledTargetBinding(object target, PropertyInfo targetPropertyInfo)
        : base(target, targetPropertyInfo)
    {
    }

    // describes how to set MyProperty on MyView
    protected override void SetValueImpl(object target, object value)
    {
        var view = target as View;
        if (view == null) return;

        view.Enabled = (bool)value;
    }

    // is called when we are ready to listen for change events
    public override void SubscribeToEvents()
    {
        var view = View;
        if (view == null)
        {
            //MvxBindingTrace.Trace(MvxTraceLevel.Error, "Error - checkbox is null in CheckboxCheckedTargetBinding");
            return;
        }
    }       

    // clean up
    protected override void Dispose(bool isDisposing)
    {
        base.Dispose(isDisposing);

        if (isDisposing)
        {

        }
    }
}

在setup.cs文件中注册自定义绑定类。

protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
    base.FillTargetFactories(registry);

    registry.RegisterPropertyInfoBindingFactory(
            typeof(ViewEnabledTargetBinding),
            typeof(View), "Enabled");
}

为您的视图应用绑定

 local:MvxBind="Text Age; Enabled IsEnable"  
© www.soinside.com 2019 - 2024. All rights reserved.