问题
I set IsTabStop to false on a text box and I know that this makes the control unable to receive focus, but according to the Silverlight Forums, it should still be able to receive mouse events. I have the MouseLeftButtonUp event wired and a breakpoint in my tbxTotal_MouseLeftButtonUp method, and it never gets hit during debugging. The thread in the SL Forums is pretty old now, so maybe this was changed in an update somewhere. I want a text box that can't be tabbed to, but is still editable. Should it really be this hard?
回答1:
I didn't realize this, but it seems to be the case, Additionally, I can't seem to get MouseLeftButtonUp to fire. MouseLeftButtonDown does fire though and using that you can do this hack.
<TextBox IsTabStop="False" MouseLeftButtonDown="TextBox_MouseLeftButtonDown" />
Then in code you can handle the event like this.
private void TextBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var textBox = ((TextBox) sender);
textBox.IsTabStop = true;
textBox.Focus();
textBox.IsTabStop = false;
}
It might be worth while to wrap it in a CustomControl
public class FocusableTextBox : TextBox
{
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (!IsTabStop)
{
IsTabStop = true;
Focus();
IsTabStop = false;
}
base.OnMouseLeftButtonDown(e);
}
}
回答2:
@seekerOfKnowledge: Disabling IsTabStop
on the LostFocus
is a good approach, but your re-focus hack is unnecessary. It fails to have any visible effect the first time around because the change of IsTabStop
has not yet taken effect. This approach can be also be taken with any other control.
var control = sender as Control;
if (control != null)
{
control.MouseLeftButtonDown += (sender, args) =>
{ //This event fires even if the control isn't allowed focus.
//As long as the control is visible, it's typically hit-testable.
if (!control.IsTabStop)
{
control.IsTabStop = true;
//threading required so IsTabStop change can take effect before assigning focus
control.Dispatcher.BeginInvoke(() =>
{
control.Focus();
});
}
};
control.LostFocus += (sender, args) =>
{ //Remove IsTabStop once the user exits the control
control.IsTabStop = false;
};
}
来源:https://stackoverflow.com/questions/5791470/istabstop-false-on-a-sl4-text-box