Ejrr1085
Ejrr1085

Reputation: 1071

Lost focus event in pop up not working in user control wpf

I have a pop up control inside a UserControl:

<UserControl ....>
<Popup x:Name="popUp" IsOpen="False" AllowsTransparency="True" LostFocus="popUp_LostFocus">
....
</Popup>
</UserControl>

The popup has a LostFocus Event:

private void popUp_LostFocus(object sender, RoutedEventArgs e)
{
    ...
}

But when I use the user control in a Window and the pop up lost the focus, the event not working.

Upvotes: 0

Views: 1683

Answers (2)

Ejrr1085
Ejrr1085

Reputation: 1071

Alternative with a ToggleButton:

XAML:

    <UserControl .....
            .....
            xmlns:local="clr-namespace:NameSpace.UserControl">    
                <UserControl.Resources>
                    <ControlTemplate x:Key="IconButton" TargetType="{x:Type ToggleButton}">
                        <Border>
                            <ContentPresenter />
                        </Border>
                    </ControlTemplate>
                    <local:BoolInverter x:Key="BoolInverterConverter"/>
                    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
                </UserControl.Resources>
                <ToggleButton Template="{StaticResource IconButton}" BorderBrush="Transparent" 
    Background="Transparent" Name="PopUpCalendarButton" IsChecked="False" 
IsHitTestVisible="{Binding ElementName=popUp, Path=IsOpen, Mode=OneWay, Converter={StaticResource BoolInverterConverter}}">
                   ......
                </ToggleButton> 
                <Popup x:Name="popUp" IsOpen="{Binding Path=IsChecked, ElementName=PopUpCalendarButton}"  PlacementTarget="{Binding ElementName=PopUpCalendarButton}" AllowsTransparency="True" PopupAnimation="Fade" StaysOpen="False">
                    .....       
                </Popup>
        </UserControl>

C#

namespace NameSpace.UserControl
{
    public partial class UserControlClass: UserControl
    {
     ...........
    }

    public class BoolInverter : MarkupExtension, IValueConverter
    {
        public override object ProvideValue(IServiceProvider serviceProvider)
        { return this; }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        { return !(bool)value; }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        { return !(bool)value; }
    }
}

Upvotes: 0

Funk
Funk

Reputation: 11201

Quoting MSDN on Popup.LogicalChildren:

... The child content is not added to the visual tree that contains the Popup control. Instead, the child content is rendered in a separate window that has its own visual tree when the IsOpen property is set to true.

Since the pop up is spawned in it's own window, it can't lose focus (to controls in another window). Instead register to the Closed event, occurs when the IsOpen property changes to false.

Upvotes: 2

Related Questions