Before I start, I have to say this. I have read this question. And I dont see how its a duplicate of this question that I posted a few hours ago.
My original post as it is:
I am using a few buttons in WPF for displaying images from various folders. The Click
mode for all the buttons is Hover
. For some button, after hovering, it is routed to a function OnButtonClick
. What I want to do is, ONLY after the mouse is over the button for X
seconds, the processing inside the function OnButtonClick
should be done.
XAML Code:
<Button Name="Dresses" MouseEnter="onMouseEnter" MouseLeave="onMouseLeave" Content="Dresses" Grid.Row="2" Height="25" Width="85" VerticalAlignment="Center" Grid.Column="5" FontFamily="Tahoma" FontSize="14" FontWeight="Bold" HorizontalAlignment="Center" Cursor="Hand" ClickMode="Hover">
<Button.Background>
<LinearGradientBrush>
<GradientStop Color="Yellow" Offset="0" />
<GradientStop Color="Green" Offset="1" />
</LinearGradientBrush>
</Button.Background>
</Button>
C# Code:
private void OnButtonClickDresses(object sender, RoutedEventArgs e)
{
//Code for delay
//Code which should run only if mouse on button after 5 seconds
}
PS: I am a beginner in WPF and C#. So if you can post a minimum working example I'd be actually very grateful.
Here is a sample application for you.
using System.Windows.Threading;
namespace MyWPF App
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
DateTime dt;
DispatcherTimer t;
public MainWindow()
{
InitializeComponent();
t = new DispatcherTimer();
t.Tick += new EventHandler(t_Tick);
}
private void button1_MouseEnter(object sender, MouseEventArgs e)
{
dt=DateTime.Now;
t.Interval = new TimeSpan(0, 0, 1);
t.IsEnabled = true;
}
void t_Tick(object sender, EventArgs e)
{
if ((DateTime.Now - dt).Seconds >= 5)
{
MessageBox.Show("Hello");// Here you can put your code which you want to execute after 5 seconds.
}
}
private void button1_MouseLeave(object sender, MouseEventArgs e)
{
t.IsEnabled = false;
}
}
}