简体   繁体   English

从ViewModel到View Xamarin的MVVMCross调用函数

[英]MVVMCross Calling function from the ViewModel to the View Xamarin

I want to show a popup when someone click on a button, the button is in a listview which is load from a webservice, how can I send a message to the view to call the AlertDialog function ? 当某人单击按钮时,我想显示一个弹出窗口,该按钮位于从Web服务加载的列表视图中,如何向视图发送消息以调用AlertDialog函数?

I was maybe not very clear I paste my code bellow to see what I tried : 我可能不太清楚,我在下面粘贴代码以查看尝试的内容:

In my viewmodel : 在我的视图模型中:

public void editPost(Post item)
{
    PostToEdit = item;

    // Call the popup function
}

In my view : 在我看来 :

public Dialog showEditPopup()
{
    var customView = LayoutInflater.Inflate(Resource.Layout.EditDialog, null);

    var builder = new AlertDialog.Builder(this);
    builder.SetView(customView);
    builder.SetPositiveButton("Save", SaveClicked);
    builder.SetNegativeButton("Cancel", CancelClicked);

    return builder.Create();  
}

I tried to create an onclick function to initialize my AlertDialog in the View 我试图创建一个onclick函数来在视图中初始化我的AlertDialog

var editButton = FindViewById<Button>(Resource.Id.editButton);
editButton.Click += delegate { ShowDialog(EditDialog); }; 

But the application crash because the posts aren't load at the time of the oncreate so the editButton is null and the event click cannot be set, so I want to create the popup in the viewmodel. 但是应用程序崩溃,因为在oncreate时未加载帖子,因此editButton为null且无法设置事件单击,因此我想在viewmodel中创建弹出窗口。

One way you can go about this is to set (from the view) an Action or Func callback on the VM, which will show the dialog, and it can be initiated from the VM. 解决此问题的一种方法是(在视图中)在VM上设置ActionFunc回调,该回调将显示对话框,并且可以从VM启动该对话框。
The other option would be to have an interface defined by the VM which the View will implement (for example IViewInteraction which has a method like ShowDialog(string text) . 另一个选择是具有由View将实现的VM定义的接口(例如IViewInteraction ,它具有类似于ShowDialog(string text)

I would suggest the first approach. 我建议第一种方法。

Probably there's going to be more than one place where you will need to show an alert dialog in your app. 可能会有多个地方需要在应用程序中显示警报对话框。

In MvvmCross there's a plugin to show dialogs in all platforms. 在MvvmCross中,有一个插件可以在所有平台上显示对话框。 You implement calling it from view-model and it will work on all platforms. 您实现从视图模型调用它,它将在所有平台上运行。

https://github.com/brianchance/MvvmCross-UserInteraction https://github.com/brianchance/MvvmCross-UserInteraction

I suggest you add it by NuGet 我建议您通过NuGet添加它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM