异步WPF命令绑定 [英] Asynchronous WPF Command Binding

查看:167
本文介绍了异步WPF命令绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好



我有一个使用MVVM模式的WPF应用程序,我的WPF客户端应用程序中也有一个按钮绑定到ICommand实现,当命令仍在运行时,如何使UI响应?



以下是我的MVVM实现代码



Hi guys

I have a WPF application the uses the MVVM pattern, I also have a button in my WPF client application that is binded to the ICommand implementation, How do I make the UI responsive when the command is still running?

Below is my code for my MVVM Implementation

private void processLoginRequest()
        {
            UserService usr = new UserService();
            bool validLoginRequest;
            string test = ComputerHashval(this.OperatorPassword, this.OperatorUserID);
            //Work On....
            try
            {
                validLoginRequest = usr.ProcessLoginRequest(this.OperatorUserID, ComputerHashval(this.OperatorPassword, this.OperatorUserID));

                if (validLoginRequest == true)
                {
                    this.MenuVisibility = true;
                    this.DisplayPage = new Uri("/Views/DashboardView/Dashboard.xaml", UriKind.RelativeOrAbsolute);
                    //usr.RegisterOperatorPresence(new CurrentOperator { OperatorUserID = this.OperatorUserID, OperatorStatus = "Online" });
                }
            }
            catch (ApplicationException ex)
            {
                this.ErrPanelVissible = true;
                this.LoginFailedError = ex.Message;
            }

        }





我的ICommand Implmentation



My ICommand Implmentation

public class LoginRequest : ICommand
        {
            public event EventHandler CanExecuteChanged;
            
            private MainWindowViewModel _authenViewModel;

            public LoginRequest(MainWindowViewModel _viewModel)
            {
                this._authenViewModel = _viewModel;
                this._authenViewModel.PropertyChanged += (s, e) =>
                {
                    if (this.CanExecuteChanged != null)
                    {
                        this.CanExecuteChanged(this, new EventArgs());
                    }
                };
            }

            public bool CanExecute(object parameter)
            {
                return this._authenViewModel.OperatorPassword != null;
            }

            public void Execute(object parameter)
            {
                this._authenViewModel.processLoginRequest();
            }
        }





和我的XAML页面





and my XAML Page

<Button Content="Login" Height="40"                 Name="LogOnBtn" HorizontalAlignment="Right" Margin="0,10,10,5" Width="89" Background="#FFD0D0D0" FontWeight="Bold" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}},               Path=DataContext.ProcLoginRequest, ValidatesOnExceptions=True, NotifyOnValidationError=True}"/>





谢谢



Thanks

推荐答案

您需要单独执行命令线。唯一的问题是命令执行的中间结果可能需要与UI交互。



您不能从非UI线程调用与UI相关的任何内容。相反,您需要使用 Invoke System.Windows.Threading的方法。 Dispatcher (对于Forms或WPF)或 System.Windows.Forms.Control (仅限表单)。



您将在我过去的答案中找到有关其工作原理和代码示例的详细说明:

Control.Invoke()与Control.BeginInvoke() [ ^ ],

使用Treeview扫描仪和MD5的问题 [ ^ ]。



另请参阅有关线程的更多参考资料:

如何让keydown事件在不同的操作上运行vb.net中的线程 [ ^ ],

在启用禁用+多线程后控制事件未触发 [ ^ ]。



-SA
You need to execute the command in a separate thread. The only problem is that the intermediate results of the command execution might need to interact with the UI.

You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

—SA


这篇关于异步WPF命令绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆