2010-03-29 2 views
0

명령 속성을 통해 단추에 명령을 바인딩하고 배치 된 페이지에서 명령 바인딩을 수행합니다. execute 메서드에서 백그라운드 작업자가 포함 된 클래스의 인스턴스를 만들고 시작합니다 (이것은 긴 작업 임). 백그라운드 작업자 (bw) 클래스에는 isRunning 변수가 포함되어 있습니다.이 변수는 DoWork 메서드가 실행되기 전에 true로 설정되고 RunWorkerCompleted가 실행될 때 false로 설정됩니다. 그래서 단추가있는 페이지의 코드 뒤에서 CanExecute 메서드에서 bw가 실행되지 않으면 e.canExecute를 true로 설정하고 (isRunning = false) isRunning = true 인 경우 e.canExecute를 false로 설정합니다.WPF 명령을 사용하여 UI 컨트롤 업데이트 속도 느림

버튼을 누를 때 bw 프로세스가 오래 동안 실행되고 버튼이 비활성화됩니다. 좋습니다. 그러나 배경 작업자 (bw)가 끝나면 단추를 다시 누를 때까지 단추가 사용 가능으로 돌아 오지 않습니다. 비활성화되어 있고 (bw가 끝나면) 누를 때 활성화됩니다. bw가 끝나면 버튼이 자동으로 돌아 오지 않는 이유는 무엇입니까?

내 코드 :

<Page x:Class="GParts.Pages.MyPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes; 
    assembly=PresentationFramework.Aero"    
    xmlns:local="clr-namespace:GParts"  
    Loaded="Page_Loaded" 
    Unloaded="Page_Unloaded" 
    Height="Auto"> 

    <Page.CommandBindings> 
    <CommandBinding Command="{x:Static local:Pages.MyPage.rcmd}" 
       Executed="CommandBinding_Executed" 
       CanExecute="CommandBinding_CanExecute"/> 
    </Page.CommandBindings> 

    <...> 
    <Button Command="{x:Static local:Pages.MyPage.rcmd}" /> 

<...> 
</Page> 

페이지 뒤에 코드 :

namespace GParts.Pages 
{ 

    public partial class MyPage : Page 
    { 

    public static RoutedCommand rcmd = new RoutedCommand(); 

    private cBgWorker bw; 

    <...> 

    // ExecutedRoutedEventHandler for the custom button remove all command. 
    private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) 
    { 

      // get an isntance of the background worker class 
      bw = new cBgWorker(); 

      // start the long task 
      bw.StartTask(); 

    } 

    // CanExecuteRoutedEventHandler for the custom button remove all command. 
    private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) 
    { 
     // bw is the instance of background worker class 
     if (bw == null) 
     { 
      e.CanExecute = true; 
     } 
     else 
     { 
      e.CanExecute = !bw.isRunning;// isRunning indicates if bw is 
             //executing now   
     } 
    } 

    <...> 

} // end class 
} // end namespace 
귀하의 경우 BackgroundWorker가 완료
+0

당신은 (많은) 질문을 살펴보고 적절한 답을 표시하는 것이 좋습니다. 가장 도움이 된 답변 옆의 작은 "확인 표시"를 클릭하십시오 .... –

답변

7

, 기본적으로 CommandManager.InvalidateRequerySuggested();

, 명령은 WPF에 의해 때때로 다시 쿼리하는 전화 . 그렇지 않으면 매번 ICommand 구현시에 "CanExecute"를 호출하는 데 엄청난 오버 헤드가 발생할 것입니다. 위 메소드를 호출하면 CommandManager가 즉시 업데이트됩니다.

이렇게하면 명령이 적절하게 다시 활성화/비활성화됩니다.