How UserControl Can Detect When It Is Visible

I have a UserControl as shown below in my MainWindow:

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

therefore, it has visibility bound to the Vis property of the MainWindow ViewModel.

I am wondering, inside the UserControl ViewModel, how can I choose when visibility has changed? I would like to start the timer when it is visible, and stop it when hiding.

+6
source share
1 answer

You can connect the UIElement.IsVisibleChanged event in 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 run Timer , I do not see a problem with this code.

But, if you still want this notification to be sent to the ViewModel, you can create an ICommand in the UserMontrol ViewModel and bind 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 link to this article here if interaction triggers are something new for you.

+7
source

All Articles