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

问题描述 投票:1回答:1

我创建了一个自定义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,这根本不起作用。

关于如何继续推进这个的任何想法或建议?

提前致谢!

c# wpf xaml
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.