工作时显示UserControl

时间:2017-01-05 11:32:25

标签: c# wpf

我在C#WPF中。

我的应用程序包含一个用于加载文件的按钮。这可能需要几秒钟,所以我创建了一个循环进度条,如下所示:

enter image description here

但是当我点击加载按钮时,不会显示进度条。这似乎是线程问题,但我不知道它是如何正常工作的。

有我的代码: MainWindow.xaml:

<Window.DataContext>
    <local:MainViewModel/>
</Window.DataContext>
<Grid>
    <local:CircularProgressBar Panel.ZIndex="1"
                               Visibility="Collapsed"
                               x:Name="progressBar"/>
    <Button Content="Load file"
            Command="{Binding LoadCommand}"/>
</Grid>

MainWindow.xaml.cs:

public MainWindow()
{
    InitializeComponent();
    (DataContext as MainViewModel).OnWork += MainWindow_OnWork;
}

private void MainWindow_OnWork(object sender, bool isStart)
{
    if (isStart)
        progressBar.Visibility = Visibility.Visible;
    else
        progressBar.Visibility = Visibility.Collapsed;
}

MainViewModel.cs:

protected RelayCommand loadCommand;
private String file;
public delegate void WorkEventHandler(object sender, bool isStart);
public event WorkEventHandler OnWork;

public ICommand LoadCommand
{
    get
    {
        if (loadCommand == null)
        {
            loadCommand = new RelayCommand(Load, CanLoad);
        }
        return loadCommand;
    }
}

private void Load()
{
    OpenFileDialog opnfldlg = new OpenFileDialog();
    opnfldlg.Multiselect = false;
    if (opnfldlg.ShowDialog() == true)
    {
        if (OnWork != null)
            OnWork(this, true);

        // This is the part who takes a time
        Task<ReadResult> readTask = Task.Factory.StartNew(() => ReadImage(opnfldlg.FileName));
        Task.WaitAll(readTask);
        ReadResult result= readTask.Result;

        if (OnWork != null)
            OnWork(this, false);
    }
}

2 个答案:

答案 0 :(得分:1)

Task.WaitAll阻止UI线程,单个线程不能同时等待和更新UI。尝试使用async / await异步等待任务:

private async void Load()
{
    OpenFileDialog opnfldlg = new OpenFileDialog();
    opnfldlg.Multiselect = false;
    if (opnfldlg.ShowDialog() == true)
    {
        if (OnWork != null)
            OnWork(this, true);

        // This is the part who takes a time
        ReadResult result = await Task.Factory.StartNew(() => ReadImage(opnfldlg.FileName));

        if (OnWork != null)
            OnWork(this, false);
    }
}

答案 1 :(得分:1)

如果您想等待任务,那么您可以使用以下代码。

Task.WaitAll(readTask).ConfigureAwait(continueOnCapturedContext: false);

上面将强制任务不等待UI线程上的结果。