Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How UserControl can tell when it's visible

Tags:

c#

wpf

xaml

I have a UserControl as below in my MainWindow:

<ctrls:Login Visibility="{Binding DataContext.Vis,
                          RelativeSource={RelativeSource Mode=FindAncestor,
                                                          AncestorType=Window}},
                          Converter={StaticResource BooelanToVisibilityConverter}"/>

so it has it's visibility bound to a property Vis in the MainWindow's ViewModel.

What I am wondering is, inside the UserControl's ViewModel how can I pickup when the visibility has changed? I would like to start a timer when visible and stop it when hidden.

like image 386
Hank Avatar asked Feb 13 '14 16:02

Hank


1 Answers

You can hook UIElement.IsVisibleChanged event on userControl:

<ctrls:Login IsVisibleChanged="Control_VisibleChanged"/>

Code behind:

private void Control_VisibleChanged(object sender, 
                                        DependencyPropertyChangedEventArgs e)
{
    if ((bool)e.NewValue)
    {
       // Visible code here
    }
    else
    { 
       // Collapse code here
    }
 }

If you want to start Timer, i see no issue in doing that from code behind.

But, however if you still want that to be notified in ViewModel you can create an ICommand in UserControl ViewModel and bind to this event using interaction triggers:

<ctrls:Login>
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="IsVisibleChanged">
          <i:InvokeCommandAction Command="{Binding VisibleChangedCommand}"/>
      </i:EventTrigger>
   </i:Interaction.Triggers>
</ctrls:Login>

You can refer to this article here in case interaction triggers is something new for you.

like image 146
Rohit Vats Avatar answered Oct 15 '22 10:10

Rohit Vats