在 WinRT / Windows Store 中使用回调进行确认的可重用方法?

A reusable method for confirms in WinRT / Windows Store, using callbacks?

我有以下冗长的代码,用于在 WinRT 中执行确认对话框

IAsyncOperation<IUICommand> asyncCommand = null;

var messageDialog = new MessageDialog("Are you sure you want to delete this file?", "Delete File");

// Add commands and set their callbacks
UICommand delete = new UICommand("Delete");
UICommand cancel = new UICommand("Cancel");

messageDialog.Commands.Add(delete);
messageDialog.Commands.Add(cancel);

messageDialog.DefaultCommandIndex = 1;

IUICommand response = await messageDialog.ShowAsync();

if (response == delete)
{
    // delete file                
}

好吧,这不是 啰嗦,但如果有某种方法可以将其放入可重复使用的方法中,我会很高兴。这是我到目前为止所拥有的。

public void Confirm(String message, string title, string proceedButtonText, string cancelButtonText)
{
    IAsyncOperation<IUICommand> asyncCommand = null;

    var messageDialog = new MessageDialog(message, title);

    // Add commands and set their callbacks
    UICommand proceed = new UICommand(proceedButtonText);
    UICommand cancel = new UICommand(cancelButtonText);

    messageDialog.Commands.Add(proceed );
    messageDialog.Commands.Add(cancel);

    messageDialog.DefaultCommandIndex = 1;

    IUICommand response = await messageDialog.ShowAsync();

    if (response == proceed)
    {
        // how do I pass my function in here?           
    }
}

我可以弄清楚传递消息、按钮名称等 - 但我如何传递我的代码/函数以在其中删除?我想我的问题是如何执行 "callback" 到 运行 一些代码?

使用动作委托,在此处查看示例:https://msdn.microsoft.com/en-us/library/018hxwa8(v=vs.110).aspx

我接受了 kiewic 的回答,因为他为我指明了正确的方向。但是,我想我会在这里分享完整的代码作为答案,以防其他人想要使用它。

private async Task<IUICommand> Confirm(string message, string title, UICommand proceed, UICommand cancel, uint defaultCommandIndex = 1)
{
    var messageDialog = new MessageDialog(message, title);

    // Add commands and set their callbacks
    messageDialog.Commands.Add(proceed);
    messageDialog.Commands.Add(cancel);
    messageDialog.DefaultCommandIndex = defaultCommandIndex;

    return await messageDialog.ShowAsync();
}

这样调用确认:

await Confirm("Are you sure you want to delete this file?", "Delete File", 
    new UICommand("Delete", async (command) => {            
        // put your "delete" code here
    }), new UICommand("Cancel"));

您可以通过将 UICommand 对象的集合传递给它来进一步扩展它 - 这将允许具有两个以上选项的对话框

同时我还编写了一个警报方法,它在显示消息对话时节省了一些代码。

private async Task<IUICommand> Alert(string message, string title = "Error")
{
    var messageDialog = new MessageDialog(message, title);
    return await messageDialog.ShowAsync();
}

如果你像我一样有 web / js 背景,你可能会发现这些很有用 ;)