我创建了一个自定义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
,这根本不起作用。
关于如何继续推进这个的任何想法或建议?
提前致谢!
你的依赖属性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>