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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With