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

时间:2015-01-21 21:36:54

标签: c# callback windows-runtime windows-store-apps

我已经获得了以下用于在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?           
    }
}

我可以弄清楚传递消息,按钮名称等 - 但是如何在那里传递我的代码/函数进行删除?我想我的问题是如何做一个&#34;回调&#34;运行一些代码?

2 个答案:

答案 0 :(得分:1)

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

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背景,你可能会觉得这些很有用;)

答案 1 :(得分:0)

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