取消/隐藏框架元素的行为

时间:2019-04-09 13:16:36

标签: c# wpf xaml

我创建了一个自定义TextBlock,它在Visibility DependencyProperty指定的几秒钟后更改了ShowTime

<customUserControl:AutoHideTextBlock Text="AutoHideTextBlock" Visibility="{Binding IsVisibleEnabled, Converter={StaticResource BoolToVisConverter}}" ShowTime="3"/>

这是一个很好的解决方案,它可以工作,问题是我还有其他一些元素需要相同的行为,而对于所有这些元素我都无法真正地将其设为CustomUserControl,所以我创建了以下类来帮我解决这个问题

public class AutoHideExtension
{
    public static readonly DependencyProperty VisibilityListenerProperty =
        DependencyProperty.RegisterAttached(
            "VisibilityListener",
            typeof(bool),
            typeof(AutoHideExtension),
            new PropertyMetadata(false, VisibilityChanged));

    public static double GetVisibilityListener(DependencyObject obj)
        => (double)obj.GetValue(VisibilityListenerProperty);

    public static void SetVisibilityListener(DependencyObject obj, double value)
        => obj.SetValue(VisibilityListenerProperty, value);

    private static void VisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var element = (FrameworkElement)d;

        if (element.Visibility == Visibility.Collapsed || !IsLoaded)
            {
                return;
            }

        DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.Background)
                                    {
                                        Interval =
                                            new TimeSpan(
                                            0,
                                            0,
                                            ShowTime)
                                    };

        timer.Tick += (senderEvent, args) =>
            {
                element.Visibility = Visibility.Collapsed;
                timer.Stop();
            };

        timer.Start();
    }
}

这个想法是,我可以将此新属性附加到任何元素,并在指定时间后更改可见性,如下所示:

<TextBlock Text="TextToHide"
            helpers:AutoHideExtension.VisibilityListener="{Binding ChangesSavedEnabled}"/>

问题是我不知道如何在扩展类中将ShowTime指定为属性,并且由于没有更改Visibility,所以这根本不起作用。

关于如何继续进行下去的任何想法或建议?

谢谢!

1 个答案:

答案 0 :(得分:1)

您的依赖项属性VisibilityListener应该获取并设置一个bool值:

public static bool GetVisibilityListener(DependencyObject obj)
    => (bool)obj.GetValue(VisibilityListenerProperty);

public static void SetVisibilityListener(DependencyObject obj, bool value)
    => obj.SetValue(VisibilityListenerProperty, value);

然后可以为ShowTime定义另一个附加属性,或者可以定义包含两个属性的Blend behaviour

<TextBlock xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
          Text="TextToHide">
    <i:Interaction.Behaviors>
        <local:AutoHideExtensionBehavior VisibilityListener="{Binding ChangesSavedEnabled}" ShowTime="3" />
    </i:Interaction.Behaviors>
</TextBlock>