模仿大佬@臨魚羨上天 做打地鼠游戲,用了6個image圖片當做地鼠。點擊start后首先設定了所有image為不顯示,再random一個image設定為顯示,同時isenabled設定為true,點擊到這個image后算作打到這個地鼠,得一分。但實際觸發不了點擊事件。斷點除錯發現,isenabled一直是false。為什么啊?
namespace WpfApplication1
{
public partial class MainWindow : Window
{
Visibility Visopen = Visibility.Visible;
Visibility Visclose = Visibility.Collapsed;
DispatcherTimer dispatchertimer2 = new DispatcherTimer();
//int lv = 1000;//難度,地鼠顯示1000毫秒后消失
int ranknum;//得分
public MainWindow()
{
InitializeComponent();
mouse1.Visibility = Visclose;
mouse2.Visibility = Visclose;
mouse3.Visibility = Visclose;
mouse4.Visibility = Visclose;
mouse5.Visibility = Visclose;
mouse6.Visibility = Visclose;
ranknum = 0;
labRank.Content = "分數:" + ranknum;
mousetest.Visibility = Visclose;
mousetest.IsEnabled = true;
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{ //點擊開始后關閉所有地鼠,打開計時器,間隔2秒,隨機顯示一個地鼠
this.IsEnabled = false;
mouse1.IsEnabled = true;
mouse2.IsEnabled = true;
mouse3.IsEnabled = true;
mouse4.IsEnabled = true;
mouse5.IsEnabled = true;
mouse6.IsEnabled = true;
DispatcherTimer dispatchertimer = new DispatcherTimer();
dispatchertimer.Tick += Dispatchertimer_Tick;
dispatchertimer.Interval = new TimeSpan(0, 0, 2);
dispatchertimer.Start();
}
private void Dispatchertimer_Tick(object sender, EventArgs e)
{
//6個地鼠中隨機選擇一個,進入下一個方法
Random random = new Random();
int num=random.Next(6);
switch(num)
{
case 0: method(mouse1); return;
case 1: method(mouse2); return;
case 2: method(mouse3); return;
case 3: method(mouse4); return;
case 4: method(mouse5); return;
case 5: method(mouse6); return;
}
}
private void method(Image image)
{//關閉所有地鼠,講選擇的地鼠打開(設定Visibility為Visible,理論上這個時候點擊地鼠應該觸發點擊事件的)同時打開第二個計時器,準備關閉
List<Image> listimage = new List<Image> { mouse1, mouse2, mouse3, mouse4, mouse5, mouse6 };
foreach(Image k in listimage)
{
k.Visibility = Visclose;
}
image.Visibility = Visopen;
image.IsEnabled = true;//問題出在這里,斷點除錯發現一直是false。觸發不了點擊事件
dispatchertimer2.Tick += Dispatchertimer2_Tick;
dispatchertimer2.Interval = new TimeSpan(0,0,1);
dispatchertimer2.Start();
}
private void Dispatchertimer2_Tick(object sender, EventArgs e)
{//第二個計時器,地鼠顯示一秒后消失
mouse1.Visibility = Visclose;
mouse2.Visibility = Visclose;
mouse3.Visibility = Visclose;
mouse4.Visibility = Visclose;
mouse5.Visibility = Visclose;
mouse6.Visibility = Visclose;
dispatchertimer2.Stop();
}
//后面是6個地鼠的點擊事件
uj5u.com熱心網友回復:
又試了一下,第33行的this改成btnStart就可以了,為什么啊?轉載請註明出處,本文鏈接:https://www.uj5u.com/net/264331.html
標籤:C#
上一篇:c# 怎么將list集合里面的值都顯示在textbox里面
下一篇:c#操作word中表格的框線
