显示控件时将焦点置于文本框
有一个自定义 UserControl,其中包含一个 TextBox
。当显示 UserControl 时如何将焦点集中到文本框?我尝试在 UserControl.IsVisibleChanged
和 TextBox.IsVisibleChanged
事件上调用 TextBox.Focus
,但这没有帮助。我还能尝试什么?
似乎有什么原因导致 TextBox
失去焦点。我提到的方法通常是有效的。如何找出导致 TextBox
失去焦点的原因?我尝试监听 TextBox.LostFocus
事件,但它的参数不包含太多有价值的信息,而且我也没有在堆栈跟踪中看到以前的方法。
代码:
void TextBox1_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (this.TextBox1.IsVisible)
this.TextBox1.Focus();
}
正如我之前所说,如果我在测试项目中的类似场景中使用相同的代码,它就可以工作,但它在我的应用程序中不起作用(应用程序很大,我基本上是在修复其中的错误,并且这就是其中之一)。所以我认为问题不在于焦点设置不当(正如我在打开这个问题时所想的那样),我认为问题在于其他东西重置了焦点。我试图在这里找到它是什么:找出文本框失去焦点的原因< /a> .
There is a custom UserControl which contains a TextBox
. How do I give focus to the textbox when UserControl is shown? I've tried calling TextBox.Focus
on UserControl.IsVisibleChanged
and TextBox.IsVisibleChanged
event, but that didn't help. What else can I try?
It seems that something causes TextBox
to loose focus. The approach that I've mentioned normally works. How can I find out what causes the TextBox
to loose focus? I've tried listening to TextBox.LostFocus
event, but it's parameters don't contain much valuable information and I also don't see previous methods in the stack trace.
The code:
void TextBox1_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (this.TextBox1.IsVisible)
this.TextBox1.Focus();
}
As I've said before, it works if I use same code on a similar scenario in a test project, but it doesn't work in my application (the application is big and I am basically fixing bugs in it, and this one is amongst them). So I think that the problem isn't that focus is set improperly (as I've thought when I was opening this question), I think that the problem is that something else resets the focus. I am trying to find what it is here: Find out why textbox has lost focus .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不太确定为什么它在可见性改变时没有回来......但是当我在
IsEnabledChanged
中执行TextBox1.Focus()
时,它就像一个魅力。I'm not exactly sure why it doesnt come back on visibility changed... however when I did
TextBox1.Focus()
inIsEnabledChanged
it worked like a charm.使用UC作为桥梁,当你让UC显示出来时,然后调用一些函数来聚焦
TextBox
。Use the UC as the bridge, when you let the UC shown, then call some function to focus the
TextBox
.