UWP阻止关闭父ContentDialog的MessageDialog

时间:2017-01-02 14:30:24

标签: c# uwp

我的应用使用ContentDialog作为数据插入的平均值。换一种说法;数据表单是ContentDialog。在验证用户输入期间,应用程序应使用MessageDialog向用户提示任何错误。但是,解雇MessageDialog也会解雇ContentDialog。

以下是显示警报时的代码块:

private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
    //save item
    ValidateForm();
}

private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
}

private async void ValidateForm()
{
    //Ensure all fields are filled
    String barcode = BarcodeText.Text.Trim();
    String desc = DescText.Text.Trim();
    String cost = CostText.Text.Trim();
    String price = PriceText.Text.Trim();
    String stock = StockText.Text.Trim();

    if(barcode.Equals(String.Empty) || desc.Equals(String.Empty) ||
            desc.Equals(String.Empty) || cost.Equals(String.Empty) || 
            price.Equals(String.Empty) || stock.Equals(String.Empty))
    {
        var dialog = new MessageDialog("Please fill in all fields");
        await dialog.ShowAsync();
        return;
    }
    //check uniqueness of the barcode

}

如何阻止警报关闭父ContentDialog?

1 个答案:

答案 0 :(得分:4)

单击PrimaryButton或SecondaryButton时,ContentDialog会自动关闭。要覆盖此行为,您必须将args.Cancel属性设置为true。由于ValidateForm是异步方法,你还需要推迟,正如Raymond Chen所说。

因此,如果您不想在显示MessageDialog时关闭ContentDialog,代码将看起来像这样:

private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
    //save item
    var deferral = args.GetDeferral()
    args.Cancel = await ValidateForm();
    deferral.Complete();
}

private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
}

// Returns true if the MessageDialog was shown, otherwise false
private async Task<bool> ValidateForm()
{
    //Ensure all fields are filled
    String barcode = BarcodeText.Text.Trim();
    String desc = DescText.Text.Trim();
    String cost = CostText.Text.Trim();
    String price = PriceText.Text.Trim();
    String stock = StockText.Text.Trim();

    if(barcode.Equals(String.Empty) || desc.Equals(String.Empty) ||
            desc.Equals(String.Empty) || cost.Equals(String.Empty) || 
            price.Equals(String.Empty) || stock.Equals(String.Empty))
    {
        var dialog = new MessageDialog("Please fill in all fields");
        await dialog.ShowAsync();
        return true;
    }
    //check uniqueness of the barcode
    return false;
}