jwillmer
jwillmer

Reputation: 3799

How to set focus to a databounded TextBox in WPF when the selection change?

I have a TextBox that is databound to a TreeView. If the selected element chnages the TextBox shows me the Name of it. What i want is, set the focus to the TextBox if the selection has changed and select the text in the TextBox.

Is this possible only with WPF and when, how?
(it is no problem with a event on the treeview "OnSelectionChange" but that's not the question ;-) )

<TextBox Name="textBoxTitel" DataContext="{Binding ElementName=treeView, Path=SelectedItem}" />

Upvotes: 2

Views: 411

Answers (1)

Jon
Jon

Reputation: 437904

It cannot be done in XAML using only built-in facilities. In the end you are going to need to write code, and it really doesn't make any difference how the source file is named. But I 'll sketch out a solution that will not require code in your code-behind file.

Derive your own class MyAction from TriggerAction. Add a MyAction as an event trigger for Treeview.SelectedItemChanged to the style of your treeview. By binding to suitable dependency properties that you will define on MyAction, instruct it to set focus and select the text of your text box, e.g.

<ns:MyAction FocusControl="{Binding ElementName=textBox}" SelectAll="True" />

At least the code will be reusable.

Upvotes: 2

Related Questions