简体   繁体   English

如何使用户控件中的文本框不关注负载?

[英]How to make a Textbox in a UserControl not receive focus on Load?

I have a XAML page where, upon tapping an "Add" button, I create a UserControl and add it to my Container. 我有一个XAML页面,在其中点击“添加”按钮后,会创建一个UserControl并将其添加到我的容器中。 This UserControl has a Rectangle, a TextBox and a few buttons. 此UserControl有一个Rectangle,一个TextBox和一些按钮。 My problem is that on the first click of the "Add" button, the focus is given to the Textbox. 我的问题是,在第一次单击“添加”按钮时,焦点被赋予了文本框。 Clicking on the "Add" button repeatedly creates more UserControl instances, but focus remains on TextBox1. 反复单击“添加”按钮,将创建更多UserControl实例,但是焦点仍停留在TextBox1上。 If I now click on Textbox5, that box gets focus, but as soon as I click outside, focus returns to Textbox1. 如果现在单击Textbox5,则该框将获得焦点,但是一旦我在外部单击,焦点就会返回到Textbox1。 I would like focus to be given to textboxes, only on click. 我希望仅在单击时将重点放在文本框上。

I have tried setting IsTabStop = true in XAML, and intercepting the tapped event and setting it to false, but that doesn't have a noticeable effect. 我曾尝试在XAML中将IsTabStop = true设置为,并拦截窃听事件并将其设置为false,但这并没有明显的效果。

What worked perfectly is setting the TextBox's TabIndex = 2, and creating another button before it, and setting it's TabIndex = 1. But I lose this benefit when I set the Button's Visibility = Collapsed. 最好的方法是设置TextBox的TabIndex = 2,并之前创建另一个按钮,并将其设置为TabIndex =1。但是,当我设置Button的Visibility = Collapsed时,我失去了这一好处。 The TextBox is the left most control, so it must have the lowest TabIndex (well technically, there is a Rectangle to the left of the TextBox, but since a Rectangle is not a Control, it cannot have a TabIndex). TextBox是最左侧的控件,因此它必须具有最低的TabIndex(从技术上讲,TextBox的左侧有一个Rectangle,但是由于Rectangle不是Control,因此它不能具有TabIndex)。

How can I fix this? 我怎样才能解决这个问题?

I believe what is happening is when you are adding more controls, it is resetting the current tab stop index. 我相信发生的事情是当您添加更多控件时,它正在重置当前的制表位索引。 So every time you add a control, the TextBox of TabStop 1 is being focused on. 因此,每次添加控件时,TabStop 1的文本框都会被关注。

What you can do, is after you add the control, call Focus() on the control that you want to be focused. 您可以做的是在添加控件后,在要Focus()的控件上调用Focus()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM