2016-07-22 14 views
2

私のプログラムには、「Print Receipt」ボタンが付いた画面があります。ボタンをクリックすると、メソッドを1回だけ呼び出す必要があります。現在、ユーザーは複数の領収書を印刷することができ、私はこれを防ぐ手段を知らない。1回だけ実行されるメソッドを作成するにはどうすればよいですか?

private async void PrintReceipt() 
{ 
    await _printReceiptInteractor.PrintTerminalReceiptAsync(_receipt).ConfigureAwait(false); 
    Dispatcher.Dispatch(() => { this.Close(); }); 
} 

このメソッドを1回だけ実行する必要がありますか?

UPDATE:私はIsBusyプロパティを追加することでこの問題を修正するために管理し、と私はそこIsBusyを設定する方法、およびだけでそのメソッドを呼び出し、その後、私がしようとキャッチを使用してついに原因イムfalseにIsBusyを設定ステートメント。

+4

は、ファイルを印刷した場合は 'true'に設定_alreadyPrinted'ブール'ブール値を追加読むことをお勧めします。あなたのメソッドでは 'true'をチェックし、' return'ならばそれをチェックします。 –

答えて

2

メソッドを呼び出すGUIコントロールを無効にするか、メソッドへのエントリを追跡するためにboolなどのプロパティを作成する必要があります。

private bool _executed = false; 
private void Method() 
{ 
    if(!_executed) 
    { 
     _executed = true; 
     // ... 
    } 
} 

private readonly Button _button = new Button(); 
private void Method() 
{ 
    _button.Enabled = false; 
    // ... 
} 

private readonly object _lockObj = new object(); 
private void Method() 
{ 
    // Prevent concurrent access 
    lock(_lockObj) 
    { 
     if(!_executed) 
     { 
      _executed = true; 
      // ... 
     } 
    } 
} 
0

これを試してみてください:

private bool _printed = false; 

private async void PrintReceipt() 
{ 
    if(!_printed) 
    { 
     await _printReceiptInteractor.PrintTerminalReceiptAsync(_receipt).ConfigureAwait(false); 
     Dispatcher.Dispatch(() => { this.Close(); }); 

     _printed = true; 
    } 
} 
0
bool isbusy; 
private async void PrintReceipt() 
{ 
    isbusy = true 

    try 
    { 
     await _printReceiptInteractor.PrintTerminalReceiptAsync(_receipt) 
    } 
    finally 
    { 
     //This block will always exeute even if there is an exception 
     isbusy = false 
    } 
} 

印刷Commandをここに私はdemoe

private ICommand _printCommand; 
     public ICommand PrintCommand 
     { 
      get 
      { 
      return _printCommand ??(PrintCommand= 
        new RelayCommand(async() => await PrintReceipt(), CanExecute)); 
      } 
     } 


//Determine can execute command 
private bool CanExecute() 
{ 
     return !isbusy; 
} 

XAML

を持っています

Commandが実行できない状態、つまりシステムがビジー状態のときにボタンが無効になります。

私はMVVM

+0

ねえ、おかげで、あなたの答えは、私はちょうど今、ジュニアDEVとして開始し、より理解しやすいと明確で、かつコードベースについて、まだ混乱してイムは、すでに 「this._printReceiptCommandLazy =新しいレイジー(()=>新しいDelegateCommandをtheresの(PrintReceipt、CanPrintReceipt)); " すでにコマンド theresの "プライベートレイジー _printReceiptCommandLazy; 公共のICommand PrintReceiptCommand { のget { 戻りthis._printReceiptCommandLazy.Value;} }" はどのように私はここにあなたの提案を実装することができますか?おかげ – Reaper

+0

HERESにCanPrintReceipt方法 「CanPrintReceipt()BOOLプライベート{ 戻り_receipt = NULL;! }」 – Reaper

+0

あなたはいけない、私はあなたがあなたの 'ICommand'と' CanPrintReceipt'だけで行くことができます示唆している同じコードベースを使用する必要がありますユーザーボタンにコマンドを追加すると、作業が開始されます – Eldho

関連する問題