UserControl 如何判断它何时可见 [英] How UserControl can tell when it's visible

查看:29
本文介绍了UserControl 如何判断它何时可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主窗口中有一个 UserControl,如下所示:

I have a UserControl as below in my MainWindow:

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

因此它的可见性绑定到 MainWindow 的 ViewModel 中的属性 Vis.

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

我想知道的是,在 UserControl 的 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.

推荐答案

您可以挂钩 UIElement.IsVisibleChanged userControl 上的事件:

You can hook UIElement.IsVisibleChanged event on userControl:

<ctrls:Login IsVisibleChanged="Control_VisibleChanged"/>

背后的代码:

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

如果你想启动 Timer,我认为从后面的代码中这样做没有问题.

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

但是,如果您仍然希望在 ViewModel 中得到通知,您可以在 UserControl ViewModel 中创建一个 ICommand 并使用 interaction triggers:

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.

这篇关于UserControl 如何判断它何时可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆