繁体   English   中英

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

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

我已经从 WPF 休息了大约一年,我被这个简单的问题难住了。 我发誓有一种简单的方法可以告诉 label 在单击时聚焦到另一个控件。

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

当用户单击“标签文本”时,我希望 TextBox 获得焦点。 这可能吗?

您应该使用 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);
    }
}

首先使用 Label 而不是 TextBlock 的全部意义在于利用其关联功能,请参阅MSDN 上的参考资料

关于我的笔记,我问了一个关于如何在此处获得真正点击的问题,如果您好奇的话。

我找到了我用来做这个的代码,并想我会分享它,以防它对其他人有用。

public class LabelEx : Label
{
    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        if (Target != null)
        {
            Target.Focus();
        }
    }
}

你不能用快捷键组合吗

    <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> 

基于阅读WPF label 对应的 HTML "for" 属性,你需要一个附加的行为来做到这一点。

暂无
暂无

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

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