Fjodr
Fjodr

Reputation: 923

Detecting default button on a control

This seems very simple, but I can find nothing on a web concerning the behaviour I want to add to my custom control.

My custom control is a textBox with a list of choices. When the text entered by the user is not part of the list, a popup will appear with the list allowing the user to select a correct choice.

Sometimes, there may be a default button on the container in wich the custom control has been added. If so, when the enter key has been pressed, if the text is wrong, The popup must been displayed. If there is no default button, on enter, nothing must happen even if the text is wrong.

To be able to create this behaviour, I must be able to detect the presence of a defaultbutton in the container, and it must be done inside the c# code of the cutom control.

I hope the description is clear enough. Thanks in advance

Upvotes: 1

Views: 180

Answers (2)

Fjodr
Fjodr

Reputation: 923

Since I was unable to know what other controls I had from the custom control I chose to go like this:

I made a recursive function to find the first parent using FrameworkElement.Parent Having the parent, I could take a look at every controls it contains. As soon as I saw a button, I had to verify if IsDefault. For this one, I used the VisualTreeHelper GetChildrenCount(DependencyObject obj_Parent) and GetChild(DependencyObject obj_Parent, int childIndex). Recursivity once again...

It works very well even though it means more code to execute.

Upvotes: 0

sellmeadog
sellmeadog

Reputation: 7517

Have you thought about implementing an MVVM approach and the Command pattern? So long as your view model knows what the choices are, you can bind the default button to a command. So long as the commands CanExecute handler returns false, i.e., an appropriate choice has not been entered/selected, the button will be disabled and won't respond to the user pressing enter.

Upvotes: 1

Related Questions