In my WPF MVVM Project I have a button that triggers a function that should add a node to a xml and then set the focus to a textbox. My question is, how can i receive a reference to a control?
View:
<Button Command="{Binding Path=ButtonAddCategory_Click}" />
ViewModel:
RelayCommand buttonAddCategory_Click;
public ICommand ButtonAddCategory_Click
{
get
{
return buttonAddCategory_Click ?? (buttonAddCategory_Click = new RelayCommand(param => this.AddCategory(),
param => true));
}
}
public void AddCategory()
{
...
//get the "node" -> reference?
XmlNode selectedItem = (XmlNode)treeView.SelectedItem;
..
//add the node to the xml
..
//change focus -> reference?
textBoxTitel.Focus();
textBoxTitel.SelectAll();
}
Don't do it in the ViewModel. The ViewModel shouldn't know anything about the view.
You can do it in code-behind:
handle the
TreeView.SelectedItemChanged
event in code-behind, and update aSelectedItem
property on the ViewModel (you could also do it with an attached behavior)to focus the
TextBox
, raise an event from the ViewModel and handle it in code-behind:ViewModel:
Code-behind:
You could use the
FocusManager.FocusedElement
attached property to handle ensuring theTextBox
receives focus.As for your second part (
textBox.SelectAll()
) you may have to work on a behavior or attached property of your own that handles the focusing and selecting in one fell swoop.