XAML 如何禁用一个按钮后,点击只有3秒钟在WinUI 3应用程序?

km0tfn4u  于 2022-12-16  发布在  其他
关注(0)|答案(1)|浏览(157)

我有一个按钮,我想禁用3秒钟,这样它就不会被滥用。我想添加一个Timer(3000);内的Click事件,但我发现的示例代码是使用过时的方法,是行不通的。我尝试了另一个代码(可以在下面找到),但这抛出System.Runtime.InteropServices.COMException: 'The application called an interface that was marshalled for a different thread. (0x8001010E (RPC_E_WRONG_THREAD))'错误。

private void CodeButton_Click(object sender, RoutedEventArgs e)
{
    CodeButton.IsEnabled = false;
    var timer = new Timer(3000);
    timer.Elapsed += (timer_s, timer_e) =>
    {
            CodeButton.IsEnabled = true;
            timer.Dispose();

    };
    timer.Start();
    Launcher.LaunchUriAsync(new Uri("https://www.hoppie.nl/acars/system/register.html"));
}
oknrviil

oknrviil1#

你需要使用主线程(示例化UI组件的线程)来更新UI。你得到这个错误是因为计时器将与另一个线程一起工作,而不是主线程。
您可以这样做:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    try
    {
        // You can update the UI because
        // the Click event will use the main thread.
        this.Button.IsEnabled = false;

        List<Task> tasks = new();
        // The main thread will be released here until
        // LaunchUriAsync returns.
        tasks.Add(Launcher.LaunchUriAsync(new Uri("https://www.hoppie.nl/acars/system/register.html")));
        tasks.Add(Task.Delay(3000));
        await Task.WhenAll(tasks);
        // The main thread will be back here.
    }
    finally
    {
        // This will enable the button even if you face exceptions.
        this.Button.IsEnabled = true;
    }
}

相关问题