0

WPF 和 c# 爱好者的新手...

出于某种原因,我无法在按下按钮后和调用 SOAP 之前立即运行 loadingAnimation(或任何其他)函数。

我的xml:

    <Grid>
    <TextBox Height="220" HorizontalAlignment="Left" Margin="12,79,0,0" Name="txtResults" VerticalAlignment="Top" Width="337" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="12,29,0,0" Name="txtServiceTag" VerticalAlignment="Top" Width="120" />
    <CheckBox Content="This computer's service tag" Height="16" HorizontalAlignment="Left" Margin="151,32,0,0" Name="chkThisST" VerticalAlignment="Top" Checked="chkThisST_Checked" Unchecked="chkThisST_Unchecked"/>
    <Button Content="Get Info" Height="23" HorizontalAlignment="Left" Margin="12,324,0,0" Name="btnGetInfo" VerticalAlignment="Top" Width="75" Click="btnGetInfo_Click" />
    <my:LoadingAnimation HorizontalAlignment="Center" Margin="128,154,419,127" VerticalAlignment="Center" Name="loadingAnimation" Visibility="Hidden" />
    </Grid>

我的.cs:

    private void btnGetInfo_Click(object sender, RoutedEventArgs e)
    {
        txtResults.Text = "Retrieving information..."; 
        ShowHideLoading();
        SoapCall();
        ShowHideLoading();
    }

我的 SoapCall() 似乎在 txtResults.Text 有时间填充之前运行。SoapCall() 大约需要 5 秒钟才能返回一条消息。我已经弄乱了对象的顺序,但无济于事。

任何帮助表示赞赏!

4

2 回答 2

1

原因是SoapCall()阻塞了 UI 线程。换句话说,在它完成之前 - 不会调用任何 UI 操作。

您可以通过将SoapCall()内部放入BackgroundWorker来解决此问题。然后, ShowHideLoading可以将其放入RunWorkerCompleted事件中。

这是一个关于如何使用 BackgroundWorker的示例

于 2013-01-26T18:38:39.577 回答
0

当您在主线程(在本例中为调用 _Click 方法的线程)上执行操作时,UI 不会真正更新,直到调用完成,并且框架会提醒 UI 重绘自身。您从未看到更新的原因是因为 SoapCall 阻止了主线程执行任何更新。

为了使其正常工作,我建议更新 UI,分叉一个新线程来执行 Soap 调用,然后在操作完成后,将 UI 重置回其原始状态。

您可能还想了解如何正确使用 Dispatcher 对象,因为 WPF 要求所有 UI 更新都在主线程上进行。Dispatcher 允许您强制一段代码在特定线程上运行。

于 2013-01-26T18:39:03.617 回答