首页 > 解决方案 > uwp 获取自定义媒体控件中视觉状态更改的通知

问题描述

在我的 uwp 应用程序中,我有自定义媒体传输控件,我想在我的控件出现和从屏幕上消失时得到通知,这样我就可以匹配光标的出现和消失。

这是我迄今为止尝试过的:

从我的控件风格的generic.xaml中,我发现遵循VisualStateGroup控制控件的淡入和淡出。

<VisualStateGroup x:Name="ControlPanelVisibilityStates">
    <VisualState x:Name="ControlPanelFadeIn">
        <Storyboard>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity" Storyboard.TargetName="ControlPanel_ControlPanelVisibilityStates_Border">
                <EasingDoubleKeyFrame KeyTime="0" Value="0" />
                <EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="1" />
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimation Storyboard.TargetProperty="Y" Storyboard.TargetName="TranslateVertical" From="50" To="0.5" Duration="0:0:0.3" />
        </Storyboard>
    </VisualState>
    <VisualState x:Name="ControlPanelFadeOut">
        <Storyboard>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity" Storyboard.TargetName="ControlPanel_ControlPanelVisibilityStates_Border">
                <EasingDoubleKeyFrame KeyTime="0" Value="1" />
                <EasingDoubleKeyFrame KeyTime="0:0:0.7" Value="0" />
            </DoubleAnimationUsingKeyFrames>
            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="IsHitTestVisible" Storyboard.TargetName="ControlPanel_ControlPanelVisibilityStates_Border">
                <DiscreteObjectKeyFrame KeyTime="0" Value="False" />
            </ObjectAnimationUsingKeyFrames>
            <DoubleAnimation Storyboard.TargetProperty="Y" Storyboard.TargetName="TranslateVertical" From="0.5" To="50" Duration="0:0:0.7" />
        </Storyboard>
    </VisualState>
</VisualStateGroup>

所以我想我应该在我的OnApplyTemplate方法中获取这个组,然后将状态更改事件分配给它。

protected override void OnApplyTemplate()
{
    //other irrelivent code
    ControlsFade = (VisualStateGroup)GetTemplateChild("ControlPanelVisibilityStates");
        ControlsFade.CurrentStateChanged += 
    ControlsFade_CurrentStateChanged;
    base.OnApplyTemplate();
}

public class ControlFadeChangedEventArgs
{
    public bool Appeared { get; set; }
}
public event EventHandler<ControlFadeChangedEventArgs> ControlFadeChanged;

private void ControlsFade_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)
{
    bool fadein = false;
    if (e.NewState.Name == "ControlPanelFadeIn")
            fadein = true;

    ControlFadeChanged?.Invoke(this, new ControlFadeChangedEventArgs { Appeared = fadein });
}

我把它全部连接起来,并且在页面上完成了进一步的逻辑,这在这种情况下是无关紧要的。我用断点调试,发现ControlsFade_CurrentStateChanged永远不会触发。

标签: c#xamluwpvisualstatemanagervisualstates

解决方案


在我的自定义控件中,我在媒体控件的UnLoaded事件(包括 ControlsFade_CurrentStateChanged)中取消订阅与我的自定义媒体控件相关的所有事件,事实证明,每当控件进入全屏状态时,都会触发Unloaded事件,因此它删除了订阅到这个事件,因此它没有在那之后触发。所以我注释掉了 unloaded 事件,现在它按预期工作。

取消订阅事件对于防止内存泄漏很重要,请在评论中告诉我如何取消订阅而不引起此问题。


推荐阅读