简体   繁体   中英

How do I prevent TextBox or RichEditBox from losing focus after clicking on a disabled button?

The title says it all: "How do I prevent TextBox or RichEditBox from losing focus after clicking on a disabled button?"

I tried setting AllowFocusOnInteraction to false, but that only works when the button is enabled. That property works well if, say, I have a button for setting text to bold or italic. The editor will not lose focus and everything works superb. But if I were to disable that button and then click on it, the editor loses focus. This causes several new issues for me. Would love some help with this. Thanks.

Also note that I have a UWP app. Not sure if it matters, though.

Okay, so I figured out the CORRECT way to fix the issue. So the bold, italic, and underline format buttons are all within my custom toolbar. What I had to remember is that most xaml elements can be clicked on and therefore trigger a PointerPressed event so long as the element (a Grid element for example) has a background for the click to intercept. If the background is transparent the PointerPressed event will not fire.

Sooo, I made sure my toolbar had a solid background set and then I set a PointerPressed event on it. So whenever you click on the toolbar that event will fire and I simply set the e.Handled property to true;

So now because the button within the toolbar is disabled the pointer click will go to the next clickable element within the visual tree that is underneath the button that you clicked, which is my toolbar (which now has a background). When the toolbar is reached, the e.Handled event being set to true within the event handler will tell the system to do nothing further and so the RichEditBox retains its focus.

I know my writing here is very sloppy but I am sort of in a rush right now and so I will most likely come back and clean my answer up. Hope this helps someone.

wrap the disabled button in a Border or a Grid.

<Grid Tapped="DisabledButtonTapped">
    <Button IsEnabled="false"/>
</Grid>

now with help of tapped method on this grid you can set focus back to your RichEditBox.

private void DisabledButtonTapped(object sender, object args)
{
    MyRichEditBox.Focus(FocusState.Programmatic);.//use the x:Name of your richeditbox in place of "MyRichEditBox".
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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