繁体   English   中英

在通过点击键盘上的Enter触发click事件之前,我可以使用哪个事件来触发标签更新?

[英]Which event can I use to trigger an update to a label before the click event is triggered by hitting enter on the keyboard?

我有一个应用程序,当单击一个按钮时,它会执行一些非常复杂的计算。 我仍在尝试提高此代码的效率,但与此同时,我想向用户提供反馈,以表明已单击按钮并通过更新UI上的标签进行了计算。

在单击事件完成之前,UI不会更新,因此我必须将代码放入一个在触发单击事件的代码之前被调用的事件中。

到目前为止,我正在使用PreviewMouseLeftButtonDown事件,该事件在执行click事件以更新标签之前被调用。 这适用于鼠标单击。
但是,如果用户在按钮处于焦点状态时按下Enter键,则似乎从未触发或至少在触发Click事件之前未触发PreviewKeyDownKeyDown事件。

当按下Enter键时,我可以使用什么事件来更新标签?或者您知道在运行Click Event的代码之前可以获取标签的另一种方式吗?

更新:我注意到在click事件之前触发了PreviewKeyDown事件,但是在click事件代码运行之前,我看不到标签更新。 我的代码没有发现任何问题。

    private void Button1_KeyDown(object sender, KeyEventArgs e)
    {
        try
        {
            if (e.Key == Key.Return || e.Key == Key.Enter)
            {
                lblMessage.Content = "Loading...";
            }
        }
        catch (Exception)
        {

        }
    }

我了解您的困境,听起来好像您是在将用户界面线程与业务逻辑捆绑在一起。 一个更有效的解决方案是创建一个新线程并在那里运行计算。 您创建您的计算类,订阅执行代码中的完成事件并启动线程。 这样,您可以在执行过程中的任何时候设置标签,因为您的业务逻辑是在与用户界面不同的线程上运行的。

为什么不使用Button的Command属性代替事件?

通过鼠标单击或输入键触发命令。

指挥总览

的CommandBinding

XAML:

 <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Button Grid.Row="0" Command="{Binding CalculationCommand}" Content=" Calculate" />
        <Label Grid.Row="1" Content="{Binding StateText}" />
    </Grid>

视图模型:

public class ViewModel : INotifyPropertyChanged
{
    private string _stateText;

    public RelayCommand CalculationCommand { get; set; }

    public string StateText
    {
        get { return _stateText; }
        set { _stateText = value;  OnPropertyChanged("StateText");}
    }

    public ViewModel()
    {
        CalculationCommand = new RelayCommand(OnCalculate);
        StateText = string.Empty;
    }

    private void OnCalculate(object obj)
    {
        StateText = "Please wait, calculating.";

        var context = TaskScheduler.Current;

        Task.Factory.StartNew(() =>{
                                        //Calculating Logic goes here   
                                   }).ContinueWith(x =>
                                                       {
                                                           StateText = "Done.";
                                                       },context);


    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

我正在使用Josh Smith的RelayCommand 文章

您可以尝试使用.Refresh()来在编辑标签后强制更新标签。 然后,您无需担心会发生其他事件-只需更改所需的内容,调用.Refresh() ,然后开始主要处理即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM