使用 MvvmCross ShowViewModel 传递复杂的导航参数

2024-04-09

即使使用此处指定的配置的 MvxJsonNavigationSerializer,我的复杂类型也不会从 Show 传递到 Init 方法v3 中导航参数的自定义类型 https://stackoverflow.com/questions/16524236/custom-types-in-navigation-parameters-in-v3/16540174#16540174

public class A
{
 public string String1 {get;set;}
 public string String2 {get;set;}
 public B ComplexObject1 {get;set;}
}

public class B
{
 public double Double1 {get;set;}
 public double Double2 {get;set;}
}

当我将对象 A 的实例传递给 ShowViewModel 方法时,我收到该对象,其中 String1 和 String2 已正确反序列化,但 CopmlexObject1 为 null。

MvvmCross如何处理复杂对象序列化?


我相信之前的答案中可能有一些小精灵 - 将作为一个问题记录:/


还有其他可能的途径来实现这种类型的复杂可序列化对象导航,仍然使用 Json 和覆盖框架的部分,但实际上我认为最好使用你自己的 BaseViewModel 来进行序列化和反序列化 - 例如使用序列化代码,例如:

public class BaseViewModel
    : MvxViewModel
{
    private const string ParameterName = "parameter";

    protected void ShowViewModel<TViewModel>(object parameter)
        where TViewModel : IMvxViewModel
    {
        var text = Mvx.Resolve<IMvxJsonConverter>().SerializeObject(parameter);
        base.ShowViewModel<TViewModel>(new Dictionary<string, string>()
            {
                {ParameterName, text}
            });
    }
}

反序列化如下:

public abstract class BaseViewModel<TInit>
    : MvxViewModel
{
    public void Init(string parameter)
    {
        var deserialized = Mvx.Resolve<IMvxJsonConverter>().DeserializeObject<TInit>(parameter);
        RealInit(deserialized);
    }

    protected abstract void RealInit(TInit parameter);
}

然后是这样的 viewModel:

public class FirstViewModel
    : BaseViewModel
{
    public IMvxCommand Go
    {
        get
        {
            return new MvxCommand(() =>
                {
                    var parameter = new A()
                        {
                            String1 = "Hello",
                            String2 = "World",
                            ComplexObject = new B()
                                {
                                    Double1 = 42.0,
                                    Double2 = -1
                                }
                        };
                    ShowViewModel<SecondViewModel>(parameter);
                });
        }
    }
}

可以导航到类似的内容:

public class SecondViewModel
    : BaseViewModel<A>
{
    public A A { get; set; }

    protected override void RealInit(A parameter)
    {
        A = parameter;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 MvvmCross ShowViewModel 传递复杂的导航参数 的相关文章

随机推荐