2011-07-27 3 views
3

이 단추에서 스팸 클릭을 거부하는 단추를 비활성화하려고합니다.코드로 WPF- 컨트롤 새로 고침

렌더링 대리인 새로 고침을 사용하여 컨트롤을 호출했지만 활성화 된 것으로 나타납니다. connect() - 버튼이 활성화 된 것으로 표시되는 약 4 초가 걸립니다.

어디에 문제가 있습니까?

public static class ExtensionMethods 
{ 

    private static Action EmptyDelegate = delegate() { }; 


    public static void Refresh(this UIElement uiElement) 
    { 
     uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate); 
    } 
} 


private void buttonConnect_Click(object sender, RoutedEventArgs e) 
{ 
    this.Cursor = Cursors.Wait; 
    buttonConnect.IsEnabled = false; 
    buttonConnect.Refresh(); 

    if (buttonConnect.Content.Equals("Connect")) 
    { 
     connect(); 
    } 
    else 
    { 
     disconnect(); 
    } 
    buttonConnect.IsEnabled = true; 
    buttonConnect.Refresh(); 
    this.Cursor = Cursors.Arrow; 
} 

답변

4

나타나 모두에서 발생하기 때문에 예를 들어,은을 사용합니다 (UI 사이에-, 당신은 백그라운드 스레드에서 작업을 실행하는 데 필요한 업데이트 및 완료에 다시 UI를 변경 할 시간이 없습니다 UI 스레드 BackgroundWorker에는 이미 RunWorkerCompleted 이벤트가 있음).

button.IsEnabled = false; 
var bw = new BackgroundWorker(); 
bw.DoWork += (s, _) => 
{ 
    //Long-running things. 
}; 
bw.RunWorkerCompleted += (s,_) => button.IsEnabled = true; 
bw.RunWorkerAsync(); 
+0

+1 내가 본 많은 해제합니다. 이것은 제가 본 가장 유연하고 믿을만한 것입니다. –

0

메서드의 우선 순위를 실제로 렌더링하지 않는 렌더링으로 설정합니다.

내가 렌더링하는 데, 여기 취할 최선의 조치를 할 것입니다 비동기 호출을 사용하여 레이아웃 엔진의 시간을주는 말을

:

private void buttonConnect_Click(object sender, RoutedEventArgs e) 
{ 
    this.Cursor = Cursors.Wait; 
    buttonConnect.IsEnabled = false; 

    Action action = buttonConnect.Content.Equals("Connect") ? connect : disconnect; 

    new Action(() => { 
     action(); 
     Dispatcher.Invoke(() => 
      { 
       buttonConnect.IsEnabled = true; 
       this.Cursor = Cursors.Arrow; 
      }); 
    }).BeginInvoke(null, null); 
} 
1

더 나은 대신 이벤트와 장난의 이유는 ICommand의 바인딩을 사용하지 거기 당신은 당신이 참/거짓이 활성화할지 여부에 따라 반환 할 수 CanExecute를 구현할 수/SO에이 질문에 버튼 답변

Great example here on ICommand

+0

내 투표가 여기 있습니다. WPF UI를 구식 스타일로 관리하지 마십시오. 정확히 –

+0

. WPF가 이미 좋은 ICommand 바인딩을 가지고있는 UI 상태를 관리하기위한 더 많은 코드! –

관련 문제