【问题标题】:Clicking on a Label to focus another control in WPF单击标签以聚焦 WPF 中的另一个控件
【发布时间】:2024-01-09 06:08:01
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# wpf xaml click label


    【解决方案1】:

    你应该使用 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 的全部意义在于利用其关联功能,请参阅reference on MSDN

    关于我的笔记,我问了一个关于如何获得真正点击的问题over here,如果你好奇的话。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      【解决方案3】:

      你不能用快捷键组合吗

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

      【讨论】:

        【解决方案4】:

        根据阅读 WPF label counterpart for HTML "for" attribute,您需要附加的行为来执行此操作。

        【讨论】:

          最近更新 更多