egse
egse

Reputation: 179

How to receive focus when clicking on the background of a stackpanel?

I have a UserControl which contains a Label and a TextBox. Both are placed inside a stackpanel which is placed in a border.

I now want to receive an Event when the mouse clicks somewere inside the stackpanel or the border. I tried several things, as using transparent Backgrounds, different Events like ismousedirectlyover etc.

Is there a way i can solve this?

Upvotes: 1

Views: 945

Answers (2)

Alberto
Alberto

Reputation: 15941

1) Add an handler for the MouseLeftButtonDown to the border:

<Border MouseLeftButtonDown="Border_MouseLeftButtonDown">
    <StackPanel Background="Transparent">
        <TextBox x:Name="Text" />
    </StackPanel>
</Border>

2) Set the focus manually to the TextBox:

private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Text.Focus();
}

make sure to set the background of the stackpanel to transparent.

Upvotes: 0

aledustet
aledustet

Reputation: 1001

You can try by capturing the mousedown event inside your textbox, your label and your stackpanel and bind them all directly to the same method, you will allways get the mousedown event independent on where you clicked. You can also try to set the

Panel.Zindex 

property to a higher number in the stackpanel and then only capture the mousedown event on it.

Upvotes: 3

Related Questions