2011-04-28 96 views
13

我已經從WPF中休息了大約一年,我被這個簡單的問題困住了。我發誓,有一種簡單的方法可以讓標籤在點擊時專注於另一個控件。點擊一個標籤將焦點集中在WPF中的另一個控件

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

當用戶點擊「標籤文本」時,我希望文本框獲得焦點。這可能嗎?

回答

15

你應該利用目標屬性:

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

擺在首位,而不是一個TextBlock使用標籤的整點是利用其關聯的功能,請參閱reference on MSDN

關於我的筆記,我問了一個關於如何獲得真正的點擊的問題over here,如果你很好奇。

2

我發現了我用於此目的的代碼,並認爲如果它對其他人有用,我會分享它。

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

注[標籤的目標屬性(http://msdn.microsoft.com/en-us/library/system.windows.controls .label.target.aspx)可能允許您在不定義自己的依賴項屬性的情況下執行此操作。 – 2011-04-28 22:48:05

+0

好的電話..你是對的。我會更新代碼。 – 2011-04-28 23:29:01

1

你不能做到這一點與快捷鍵組合

<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> 
相關問題