14

I have taken a break from WPF for about a year and I am stumped by this simple problem. I swear there was an easy way to tell a label to focus to another control when it is clicked.

 <StackPanel>
    <Label Target="TextBox1">Label Text</Label>
    <TextBox Name="TextBox1" />
</StackPanel>

When the user clicks on "Label Text" I want the TextBox to receive focus. Is this possible?

H.B.
  • 166,899
  • 29
  • 327
  • 400
Shaun Bowe
  • 9,840
  • 11
  • 50
  • 71

4 Answers4

17

You should make use of the Target property:

<Label Content="_Stuff:" Target="{x:Reference TextBox1}"
       MouseLeftButtonUp="Label_MouseLeftButtonUp"/>
<TextBox Name="TextBox1" />
private void Label_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    if (e.ClickCount == 1) //Note that this is a lie, this does not check for a "real" click
    {
        var label = (Label)sender;
        Keyboard.Focus(label.Target);
    }
}

The whole point of using a Label in the first place instead of a TextBlock is to make use of its associative functionality, see the reference on MSDN.

About my note, i asked a question about how to get a real click over here, if you are curious.

Community
  • 1
  • 1
H.B.
  • 166,899
  • 29
  • 327
  • 400
2

I found the code I used to use for this and figured I would share it in case it is useful for anyone else.

public class LabelEx : Label
{
    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        if (Target != null)
        {
            Target.Focus();
        }
    }
}
Shaun Bowe
  • 9,840
  • 11
  • 50
  • 71
  • 1
    Note the [Label's Target property](http://msdn.microsoft.com/en-us/library/system.windows.controls.label.target.aspx) may allow you to do this without defining your own dependency property. – Dan J Apr 28 '11 at 22:48
1

can't you do that with the shortcut key combination

    <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Label Target="{Binding ElementName=textbox1}" Content="_Name"/>
    <TextBox Name="textbox1" Height="25" Grid.Column="1" VerticalAlignment="Top"/>
</Grid> 
Kishore Kumar
  • 21,449
  • 13
  • 81
  • 113
0

Based on reading WPF label counterpart for HTML "for" attribute, you'd need an attached behavior to do that.

Community
  • 1
  • 1
Zach Johnson
  • 23,678
  • 6
  • 69
  • 86