Auto showing tips and closing popup when lost focus

Posted by darkwindkey on Stack Overflow See other posts from Stack Overflow or by darkwindkey
Published on 2014-08-24T16:14:12Z Indexed on 2014/08/24 16:20 UTC
Read the original article Hit count: 342

Filed under:
|
|
|
|

I have two elements: a TextBox, and a Popup, where the popup contains a tree view to show some tips according to text of TextBox. When the textBox got the KeyDown Event, the KeyDown directly executes pup.IsOpen=true to show the popup tips.

However, I also want to show the popup tips when the mouse on clicking the TextBox, and auto closing the popups when the mouse click on any place (besides the TextBox and the TreeView in Popup).

I have tried some cases but do not works fine.

Case1: Add pup.IsOpen=true; in TextBox.PreviewMouseUp, the popup will stay opening, even if I click any other place in the window.

Case2: Add pup.IsOpen=true in TextBox.PreviewMouseDown, the popup tips only shows on keep clicking the Mouse.

Case3: Using CheckBox with Binding IsChecked to Popup.IsOpen works fine. but the tips is listed according to the content of the TextBox, therefore the checkbox is not editable for user...

Here is my code now:

<Window x:Class="popUpTesting.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox 
            Name="SearchBox" 
            HorizontalAlignment="Center" 
            TextWrapping="Wrap" 
            Text="TextBox" 
            VerticalAlignment="Center" 
            KeyDown="SearchBox_KeyDown" PreviewMouseUp="SearchBox_PreviewMouseUp"
            />

        <Popup 
            Placement="Bottom" 
            AllowsTransparency="True"  
            PopupAnimation="Fade" 
            StaysOpen="false"
            x:Name="pup" 
            PlacementTarget="{Binding ElementName=SearchBox}"
            IsOpen="False"
            >
            <Grid>
                <TreeView HorizontalAlignment="Left" Height="200" VerticalAlignment="Top" Width="200">
                    <TreeViewItem Header="A">
                        <TreeViewItem Header="A1"/>
                    </TreeViewItem>
                    <TreeViewItem Header="B"></TreeViewItem>
                    <TreeViewItem Header="C"></TreeViewItem>
                    <TreeViewItem Header="D"></TreeViewItem>
                </TreeView>
            </Grid>
        </Popup>
    </Grid>
</Window>

and the event functions:

private void SearchBox_KeyDown(object sender, KeyEventArgs e)
{
    pup.IsOpen = true;        
}

private void SearchBox_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
    pup.IsOpen = true;
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf