2

I have tabItems with TextBox on their headers. I use LostFocus and MouseDoubleClick events to set the text to the TextBox.

<TabControl>
                <TabItem Width="50">
                    <TabItem.Header>
                        <TextBox Text="text" IsReadOnly="True" LostFocus="TextBox_LostFocus" MouseDoubleClick="TextBox_MouseDoubleClick"/>
                    </TabItem.Header>
                </TabItem>
</TabControl>

    private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        TextBox text_box = sender as TextBox;
        if (text_box == null) { return; }

        text_box.IsReadOnly = false;
        text_box.SelectAll();
    }

    private void TextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        TextBox text_box = sender as TextBox;
        if (text_box == null) { return; }

        text_box.IsReadOnly = true;
    }

LostFocus event happens if only you click on the TabItem header area outside the TextBox or on enother TabItem. Clicking the tab item content area doesn't fire lost focus event.

How to make the TextBox to lose focus when user click any area outside the TextBox?

4

2 に答える 2

3

フォーカスを失う、つまり、タブのコンテンツ (ターゲット) 内でフォーカスを取得するには:

  1. 対象のFocusableをtrueに設定
  2. ターゲットはヒット テスト可能である必要があります。ターゲットの背景は null であってはなりません。
  3. マウス クリックに反応するように、PreviewMouseDown イベント (注: MouseDown ではありません) にイベント ハンドラーを追加します。3ステップ以外の場合、アプリケーションはTABキーのみに反応します。

    <TabControl>
        <TabItem Width="50">
            <TabItem.Header>
                <TextBox 
                    Text="text" IsReadOnly="True" 
                    LostFocus="TextBox_LostFocus"
                    MouseDoubleClick="TextBox_MouseDoubleClick"/>
            </TabItem.Header>
            <Border Focusable="True" Background="Transparent" PreviewMouseDown="Border_PreviewMouseDown"/>
        </TabItem>
    </TabControl>
    
    
    private void Border_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        var uiElement = sender as UIElement;
        if (uiElement != null) uiElement.Focus();
    }
    
于 2011-10-26T06:59:05.720 に答える
1

フォーカスを失うには、まず要素フォーカスが必要です。おそらく代替手段として、要素が初期化されるときに適切な場所に要素のフォーカスを与えることができます。たとえば、次のようになります。

変化する

<TextBox Text="text" IsReadOnly="True" LostFocus="TextBox_LostFocus" MouseDoubleClick="TextBox_MouseDoubleClick"/>

<TextBox x:Name="MyTextBox" Text="text" IsReadOnly="True" LostFocus="TextBox_LostFocus" MouseDoubleClick="TextBox_MouseDoubleClick"/>

そして、コンストラクターで FocusManager を使用して、フォーカスされた要素を設定します。

...
FocusManager.SetFocusedElement(MyTextBox.Parent, MyTextBox);
...

MSDN のFocus Overviewは優れたリソースです。キーボード フォーカスと論理フォーカスを区別することも重要です。

于 2011-10-26T05:58:35.317 に答える