Set focus on TextBox in WPF from view model

后端 未结 21 2500
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 06:21

I have a TextBox and a Button in my view.

Now I am checking a condition upon button click and if the condition turns out to be false, displ

21条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 06:35

    In my case, the FocusExtension didn't work until I change the method OnIsFocusedPropertyChanged. The original one was working only in debug when a break point stopped the process. At runtime, the process is too quick and nothing happend. With this little modification and the help of our friend Task, this is working fine in both scenarios.

    private static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      var uie = (UIElement)d;
      if ((bool)e.NewValue)
      {
        var action = new Action(() => uie.Dispatcher.BeginInvoke((Action)(() => uie.Focus())));
        Task.Factory.StartNew(action);
      }
    }
    

提交回复
热议问题