Reputation: 1691
I have created a custom TextBlock
that changes the Visibility
after some seconds specified by a DependencyProperty
ShowTime
:
<customUserControl:AutoHideTextBlock Text="AutoHideTextBlock" Visibility="{Binding IsVisibleEnabled, Converter={StaticResource BoolToVisConverter}}" ShowTime="3"/>
This is a nice solution and it works, the problem is that I have several other elements that needs the same behaviour and I cannot really make it a CustomUserControl
for all of them, I have created the following class to help me with that:
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();
}
}
The idea is that I can attach this new property to any element and change the visibility after the specified time, something like follows:
<TextBlock Text="TextToHide"
helpers:AutoHideExtension.VisibilityListener="{Binding ChangesSavedEnabled}"/>
The problem is that I don't know how to specify the ShowTime
as property in the extension class, and that this is simply not working since is not changing the Visibility
.
Any Ideas or suggestions on how I can continue forward with this?
Thanks in advance!
Upvotes: 1
Views: 45
Reputation: 169200
Your dependency property VisibilityListener
should get and set a bool
value:
public static bool GetVisibilityListener(DependencyObject obj)
=> (bool)obj.GetValue(VisibilityListenerProperty);
public static void SetVisibilityListener(DependencyObject obj, bool value)
=> obj.SetValue(VisibilityListenerProperty, value);
You could then define another attached property for the ShowTime, or you could define a Blend behaviour that contains two properties:
<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>
Upvotes: 1