WPF利用委托与事件实现VM对View中控件的调用

xiaoxiao2021-02-28  98

WPF结合MVVM模式,可以实现界面与代码的完全分离,非常便于开发与维护,但对于某些特定需求,例如TextBox需要Focus获得光标,或者全选其中的文本,这时候就比较难了,因为VM中完全拿不到控件对象,也很难调用Focus()与SelectAll()方法,但也不是完全不可以,有一种利用委托与事件实现的方法,不知道是否有背MVVM分离思想,具体方法如下:

View.xaml:

<TextBox Name="InputBox" Text="{Binding InputStr}"/> View.xaml.cs:

public partial class MainView : UserControl { public MainView() { InitializeComponent(); this.Loaded += MainView_Loaded; } private void MainView_Loaded(object sender, RoutedEventArgs e) { InputBox.Focus(); InputBox.SelectAll(); var vm = DataContext as MainViewModel; vm.ControlFocusEvent += View_ControlFocus; } private void View_ControlFocus(string controlName) { switch (controlName) { case "InputBox": InputBox.Focus(); InputBox.SelectAll(); break; default: break; } } }

VM:

public delegate void ControlFocusHandler(string controlName); public event ControlFocusHandler ControlFocusEvent; public void Focus() { ControlFocusEvent.Invoke("InputBox"); }

转载请注明原文地址: https://www.6miu.com/read-32710.html

最新回复(0)