2016-08-15 60 views
0

我試圖在我的WPF應用程序中實現一個進度條。Progerssbar不會更新

所以我說一個我的看法

 <ProgressBar Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" Height="31" 
       Minimum="0" 
       Maximum="50" 
      Value="{Binding CurrentProgress}" /> 

我的視圖模型得到了一個新的屬性:

public int CurrentProgress 
{ 
    get { return mCurrentProgress; } 
    set 
    { 
    if (mCurrentProgress != value) 
    { 
     mCurrentProgress = value; 
     RaisePropertyChanged("CurrentProgress"); 
    } 
    } 
} 

當我的負荷命令執行時,它會引發對加載的每一個文件的生成的事件。 而此事件的事件處理程序添加+1這樣的「CurrentProgress」屬性:

private void GeneratedHandler(object sender, EventArgs eventArgs) 
{ 
    CurrentProgress++; 
} 

但我沒有看到欄上任何進展。有人看到我做錯了嗎? 在此先感謝!

+0

你在UI線程中執行工作。 UI線程在您執行其中的工作時無法更新UI。您正在使用該線程來加載文件。 – Will

回答

1

我試過重現你的問題,但它在這裏工作得很好。

反正有你可以按照以下幾個步驟:

  1. 確保您不加載UI線程上的文件。如果是,請看「在執行冗長任務時顯示進度」this的文章。

  2. 確保您WindowDataContext是正確的,你的ViewModel實現System.ComponentModel.INotifyPropertyChanged和你RaisePropertyChanged方法是正確的。


下面是我使用的代碼(不要複製並粘貼app.xml的):

視圖模型:

public class MainWindowViewModel : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    public void NotifyPropertyChanged([CallerMemberName] string property = "") 
    { 
     if(PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(property)); 
     } 
    } 

    private int _Progress; 
    public int Progress 
    { 
     get 
     { 
      return _Progress; 
     } 

     set 
     { 
      if(value != Progress) 
      { 
       _Progress = value; 

       NotifyPropertyChanged(); 
      } 
     } 
    } 
} 

MainWindow.xml

<Window x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525" 
    DataContext="{StaticResource ResourceKey=ViewModel_MainWindow}"> 
<Grid> 
    <ProgressBar Value="{Binding Progress}" Minimum="0" Maximum="50" /> 
</Grid> 

而且的App.xaml

<Application x:Class="WpfApplication1.App" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     StartupUri="MainWindow.xaml" 
     xmlns:local="clr-namespace:WpfApplication1" > <!--change the namespace to the one where you ViewModel is--> 
<Application.Resources> 
    <local:MainWindowViewModel x:Key="ViewModel_MainWindow" /> <!--important--> 
</Application.Resources> 

+0

我忘了將工作加載到後臺線程。它現在按預期工作,謝謝! – user3292642