在 UI 繁忙时忽略用户输入

我将通过在示例应用程序中使用两个按钮来模拟我的问题。在我的实际案例中,我有一个用户控件和一个选项卡控件。当按下用户控件上的按钮时,我正在尝试获取父窗口并禁用它,并在UI上执行一些工作1分钟。UI可用后,我将启用父窗口。


我的问题是,当父窗口被禁用并且当用户单击选项卡控件时,只要UI繁忙,它就不会无响应。但是,一旦 UI 完成其工作,所有用户输入都会被考虑在内,并且它会自行切换选项卡。我想在UI繁忙时忽略用户输入,请帮忙。有什么建议吗?


在示例应用程序中,此处是 xaml


<StackPanel Orientation="Vertical">

        <Button Height="20" Width="180" Click="Button_Click"

                >Hello</Button>

        <Button Height="20" Width="180" Click="Button_Click_1">Do Nothing</Button>

    </StackPanel>

在 xaml.cs 文件中,此处是代码。看到我正在禁用窗口,但是当按下按钮时,我在UI免费后自动收到hello消息。


private void Button_Click(object sender, RoutedEventArgs e)

        {

            MessageBox.Show("Hello");

        }


        private void Button_Click_1(object sender, RoutedEventArgs e)

        {

            Window.GetWindow(this).IsEnabled=false;

            Thread.Sleep(5000);

            Window.GetWindow(this).IsEnabled=true;

        }


拉风的咖菲猫
浏览 66回答 1
1回答

米琪卡哇伊

只需在新线程中运行长时间运行的代码&nbsp; &nbsp; private void Button_Click_1(object sender, RoutedEventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Task.Run(() =>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.Dispatcher.Invoke(() =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Window.GetWindow(this).IsEnabled = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread.Sleep(5000);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; finally&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.Dispatcher.Invoke(() =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Window.GetWindow(this).IsEnabled = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }预期结果https://i.stack.imgur.com/dgRSm.gif
打开App,查看更多内容
随时随地看视频慕课网APP