简体   繁体   English

单击 Label 以聚焦 WPF 中的另一个控件

[英]Clicking on a Label to focus another control in WPF

I have taken a break from WPF for about a year and I am stumped by this simple problem.我已经从 WPF 休息了大约一年,我被这个简单的问题难住了。 I swear there was an easy way to tell a label to focus to another control when it is clicked.我发誓有一种简单的方法可以告诉 label 在单击时聚焦到另一个控件。

 <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.当用户单击“标签文本”时,我希望 TextBox 获得焦点。 Is this possible?这可能吗?

You should make use of the Target property:您应该使用 Target 属性:

<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 .首先使用 Label 而不是 TextBlock 的全部意义在于利用其关联功能,请参阅MSDN 上的参考资料

About my note, i asked a question about how to get a real click over here , if you are curious.关于我的笔记,我问了一个关于如何在此处获得真正点击的问题,如果您好奇的话。

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();
        }
    }
}

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> 

Based on reading WPF label counterpart for HTML "for" attribute , you'd need an attached behavior to do that.基于阅读WPF label 对应的 HTML "for" 属性,你需要一个附加的行为来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM