6

我在文本框上将 IsTabStop 设置为 false,我知道这会使控件无法接收焦点,但根据Silverlight 论坛,它应该仍然能够接收鼠标事件。我在 tbxTotal_MouseLeftButtonUp 方法中连接了 MouseLeftButtonUp 事件和一个断点,并且在调试期间它永远不会被命中。SL 论坛中的帖子现在已经很老了,所以也许这在某处的更新中被改变了。我想要一个文本框,它不能被标签,但仍然是可编辑的。真的应该这么难吗?

4

2 回答 2

3

我没有意识到这一点,但似乎是这样,此外,我似乎无法让 MouseLeftButtonUp 触发。不过,MouseLeftButtonDown 确实会触发,并且使用它您可以执行此 hack。

<TextBox IsTabStop="False" MouseLeftButtonDown="TextBox_MouseLeftButtonDown" />

然后在代码中你可以像这样处理事件。

    private void TextBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        var textBox = ((TextBox) sender);
        textBox.IsTabStop = true;
        textBox.Focus();
        textBox.IsTabStop = false;
    }

将它包装在 CustomControl 中可能是值得的

public class FocusableTextBox : TextBox
{
    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        if (!IsTabStop)
        {
            IsTabStop = true;
            Focus();
            IsTabStop = false;
        }

        base.OnMouseLeftButtonDown(e);
    }
}
于 2011-04-26T14:11:39.960 回答
1

@seekerOfKnowledge:禁用IsTabStopLostFocus一个好方法,但你的重新聚焦黑客是不必要的。由于更改IsTabStop尚未生效,因此第一次没有任何可见的效果。这种方法也可以与任何其他控制一起使用。

        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;
                };
        }
于 2012-01-03T18:31:59.930 回答