![](/img/trans.png)
[英]WPF, How to focus a TextBox element of an user control from another?
[英]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.