Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 按代码刷新WPF控件_C#_Wpf_Controls_Refresh - Fatal编程技术网

C# 按代码刷新WPF控件

C# 按代码刷新WPF控件,c#,wpf,controls,refresh,C#,Wpf,Controls,Refresh,我正在尝试禁用一个拒绝垃圾邮件的按钮单击此按钮 我使用了一个刷新委托来呈现和调用控件,但它显示为已启用。 connect()-Methode大约需要4秒钟,按钮显示为enabled(已启用) 问题在哪里 public static class ExtensionMethods { private static Action EmptyDelegate = delegate() { }; public static void Refresh(this UIElement uiEl

我正在尝试禁用一个拒绝垃圾邮件的按钮单击此按钮

我使用了一个刷新委托来呈现和调用控件,但它显示为已启用。 connect()-Methode大约需要4秒钟,按钮显示为enabled(已启用)

问题在哪里

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;
}

由于所有这些似乎都发生在UI线程上,在此期间UI没有时间更新,因此您需要在后台线程上运行任务,并在完成时再次更改UI(例如,使用已发生
RunWorkerCompleted
事件的

e、 g


您正在设置要渲染的方法的优先级,该方法实际上不进行任何渲染

我想说,在这里使用异步调用是最好的操作,让布局引擎有时间渲染:

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);
}

更妙的是,与其乱搞事件,为什么不使用ICommand绑定,在那里您可以实现CanExecute,您可以根据是否要启用/禁用按钮来返回true/false


我在这里投票。永远不要以旧的方式管理WPF UI。更多管理UI状态的代码,其中as WPF已经有了很好的ICommand绑定+我已经看到了很多关于这个问题的答案。这是我见过的最灵活、最可靠的。
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);
}