在Xamarin Forms&中定义命令方法的返回类型。 MVVM

时间:2017-03-16 06:03:42

标签: xamarin mvvm xamarin.forms

我想为一个与我的命令相关联的方法定义一个返回类型,该命令在按钮点击时执行。例如,

点击按钮,

this.Detail = ViewModel.MasterItemSelectedCommand.Execute(seleteditem);

在视图模型构造函数中,

MasterItemSelectedCommand = new Command<string>(OnMasterItemSelected);

之后,我的方法就像,

private Page OnMasterItemSelected(string seleteditem)
{
    switch (seleteditem)
    {
        case "ABC":
            return new TestDrillPageDetail("Test Drill Page Detail 1");

        case "DEF":
            return new TestDrillPageDetail("Test Drill Page Detail 2");

        case "XYZ":
            return new TestDrillPageDetail("Test Drill Page Detail 3");

        default:
            return new TestDrillPageDetail("Test Drill Page Detail 1");
    }
}

从这个方法,我想返回可以在按钮点击方法上使用的Page对象。如果我在此方法中使用Page而不是void作为返回类型,那么我收到错误,此方法的返回类型错误。

那么,有没有办法为上面的方法定义返回类型?请帮忙。

1 个答案:

答案 0 :(得分:2)

命令结构不是设计为像那样使用它。但是你可以定义一个公共方法,而不是在代码中手动调用命令。

你的方法:

Public Shared Function sha256_hash(value As [String]) As [String]
    Using hash As SHA256 = SHA256Managed.Create()
        Dim hashString = String.Empty
        Dim computedHash = hash.ComputeHash(Encoding.UTF8.GetBytes(value))
        For Each item In computedHash
            hashString = String.Concat(hashString, item.ToString("x2"))
        Next
        Return hashString
    End Using
End Function

您可以像这样定义命令:

public Page ChangeMasterItem(string selecteditem)
{
    switch (seleteditem)
    {
        case "ABC":
            return new TestDrillPageDetail("Test Drill Page Detail 1");

        // and so on ...
    }
}

在按钮点击事件中,只需使用以下方法:

public ICommand MasterItemSelectedCommand => new Command<string>((selecteditem) =>
{
    var mypage = ChangeMasterItem(selecteditem);

    // You can use mypage now if you want
});