[英]How to access focused element programmatically WPF C#
想知道如何訪問具有焦點的elements屬性。 我已經找到以下代碼來查找關注的元素:
var focusedControl = FocusManager.GetFocusedElement(this);
這似乎運作良好,在調試中“ focusedcontrol”是正確的元素,但是我不知道如何以編程方式訪問它。 就像是 :
focusedControl.Text = "txt";
我想要這樣做的原因-在與TextBoxes相同的窗口中,我有幾個構成鍵盤的Buttons。 按下按鈕后(Focusable = False),我想獲取對焦點TextBox的引用,並在TextBox.Text中插入相應的數字。
謝謝盧卡斯
GetFocusedElement()
方法返回IInputElement
而不是TextBox
。
由於FrameworkElement
實現了IInputElement
,並且Control
(和TextBox
)是從FrameworkElement
派生的,因此您只需將結果自己投射到TextBox
:
var focusedControl = FocusManager.GetFocusedElement(this);
var tBox = focusedControl as TextBox;
if (tBox != null)
tBox.Text = "txt";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.