WPF C# 用户控件页面 IsVisibleChanged 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17770680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:15:21  来源:igfitidea点击:

WPF C# User control page IsVisibleChanged event

c#wpfuser-controls

提问by what

i have some user control page , and a MainWindow , so i would like to set user control page to hidden , and once its hidden , it stops its audio from playing

我有一些用户控制页面和一个主窗口,所以我想将用户控制页面设置为隐藏,一旦隐藏,它就会停止播放音频

i know i have to do something with IsVisibleChanged event but i got stuck at how to start it?

我知道我必须对 IsVisibleChanged 事件做一些事情,但我被困在如何启动它?

Is it something like this ?

是这样的吗?

(pagename).IsVisibleChanged(object sender , RoutedEventArgs e )
 {    ap.Stop()  }

Because my user control page ( i display it within the mainwindow using a custom control ) is in my mainwindow and the user control page have some audio playing , when i click the home button that resides on the mainwindow , i'll set the user control page to hidden and show my home page , but now when it is hidden , the audio from that page is still playing , so i went to ask and some said use IsVisibleChanged event in user control page ( the 1 that plays the audio ) but i got stuck at how do i even write it cos i am new to this .

因为我的用户控制页面(我使用自定义控件在主窗口中显示它)在我的主窗口中并且用户控制页面有一些音频播放,当我单击位于主窗口上的主页按钮时,我将设置用户控件页面隐藏并显示我的主页,但是现在当它隐藏时,来自该页面的音频仍在播放,所以我去问,有人说在用户控制页面(播放音频的第一个)中使用 IsVisibleChanged 事件,但我被困在我什至如何写它因为我是新手。

回答by kmatyaszek

First solution:

第一个解决方案:

You should use DependencyPropertyChangedEventArgsas second argument and you should check NewValueproperty that indicates if page will be visible or not (msdn).

您应该使用DependencyPropertyChangedEventArgs作为第二个参数,并且应该检查NewValue指示页面是否可见的属性(msdn)。

Example:

例子:

void (pagename)_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    if (!((bool)e.NewValue))
    {
        ap.Stop();
    }
}

Hereyou find the sample solution (IsVisibleChangedExample).

在这里您可以找到示例解决方案 (IsVisibleChangedExample)。

Second solution:

第二种解决方案:

If you use MediaElement(msdn) to play the music, you should use two properties: LoadedBehavior(msdn) and UnloadedBehavior(msdn).

如果您使用MediaElement( msdn) 播放音乐,则应使用两个属性: LoadedBehavior( msdn) 和UnloadedBehavior( msdn)。

Example:

例子:

<MediaElement Name="me" Source="path to your music file" 
              LoadedBehavior="Play" UnloadedBehavior="Stop" Volume="100" />