Set focus on TextBox in WPF from view model

后端 未结 21 2596
爱一瞬间的悲伤
爱一瞬间的悲伤 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:37

    I think the best way is to keep the MVVM principle clean, so basically you must use the Messenger Class provided with the MVVM Light and here is how to use it:

    in your viewmodel(exampleViewModel.cs):write the following

     Messenger.Default.Send("focus", "DoFocus");
    

    now in your View.cs(not the XAML the view.xaml.cs) write the following in the constructor

     public MyView()
            {
                InitializeComponent();
    
                Messenger.Default.Register(this, "DoFocus", doFocus);
            }
            public void doFocus(string msg)
            {
                if (msg == "focus")
                    this.txtcode.Focus();
            }
    

    that method owrks just fine and with less code and maintaining MVVM standards

提交回复
热议问题