2012-05-22 20 views
3

下面的兩個代碼段位於不同的名稱空間中。第二個代碼的訪問修飾符是內部的。我正在做一些操作,我想計算MgmntApp進度條中的百分比和更新。我怎樣才能做到這一點?使用內部類中存在的值更新進度條

WpfApplication1

MainWindow.xaml

<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"> 
    <Grid Height="204"> 
     <ProgressBar Height="35" HorizontalAlignment="Left" Margin="57,83,0,0" Name="progressBar1" VerticalAlignment="Top" Width="346" /> 
    </Grid> 
</Window> 

我想在下面的類做了長時間運行的操作以更新進度條的值。

不同

FileParser.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Different 
{ 
    /// <summary> 
    /// </summary> 
    internal class FileParser:ImageFileParser 
    { 
     ImageFileParser.GenerateCmds() 
     { 
      percentage=change; //0 to 100 
      //long time operation 
     } 
    } 
} 

回答

1

爲什麼不直接綁定到你的FileParser類的屬性?

<ProgressBar Value="{Binding MyFileParser.PercentComplete}" ... 

然後有FileParser實施INotifyPropertyChanged的

internal class FileParser:ImageFileParser, INotifyPropertyChanged 
{ 
    private decimal _pct; 
    internal decimal PercentComplete { 
     get { return _pct; } 
     set { 
      _pct = value; 
      PropertyChanged(this, new PropertyChangedEventArgs("PercentComplete")); 
     } 
    } 
    PropertyChanged(this, new PropertyChangedEventArgs(info)); 

    ImageFileParser.GenerateCmds() 
    { 
     PercentComplete = change; //0 to 100 
     //long time operation 
    } 
} 

然後根據需要簡單地更新PERCENTCOMPLETE財產......

2

如果解析需要很長的時間,你也許想要在單獨的線程上運行它。

你可以在FileParser引發事件當進度變化和訂閱此事件在主窗口:

private void StartParsing() 
{ 
    FileParser fp = new FileParser("FileName.txt"); 
    fp.ProgressChanged += FileParser_ProgressChanged; 
    Thread t = new Thread(fp.GenerateCmds); 
    t.Start(); 
} 

private void FileParser_ProgressChanged(object sender, ProgressChangedEventArgs e) 
{ 
    // switch to the UI thread if fileparser is running on a different thread 
    Dispatcher.BeginInvoke(new Action(
          () => { progressbar.Value = e.ProgressPercentage; })); 
} 

要做到這一點,你需要將事件添加到FileParser:

internal class FileParser:ImageFileParser 
{ 
    internal event EventHandler<ProgressChangedEventArgs> ProgressChanged; 

    ImageFileParser.GenerateCmds() 
    { 
     percentage=change; //0 to 100 
     OnProgressChanged(percentage); 
     //long time operation 
    } 

    internal protected void OnProgressChanged(int percentage) 
    { 
     var p = ProgressChanged; 
     if(p != null) 
     { 
      p(this, new ProgressChangedEventArgs(percentage, null)); 
     } 
    } 
} 
+0

但fp.GenerateCmds()將被另一個名爲PrgmCmdGen的類調用。如何更新用戶界面?(我無法訪問UI的進度欄 – SHRI

+0

不要從邏輯內更新視圖。將PrgmCmdGen類訂閱到事件中,並從PrgmCmdGen類中暴露另一個ProgressChanged事件)並按照我在我的回答中所建議的那樣訂閱它。 –

+0

new ProgressChangedEventArgs(percentage));這是給錯誤。另一個參數UserState它的要求。 – SHRI