實習期間開始使用WPF,記錄一點東西,沒什麼技術含量。多線程
// 計時器this
System.Windows.Threading.DispatcherTimer ShowTimer;spa
ShowTimer = new System.Windows.Threading.DispatcherTimer();線程
ShowTimer.Tick += new EventHandler(ShowCurTimer);orm
ShowTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);事件
ShowTimer.Start();element
private void ShowCurTimer(object sender, EventArgs e)string
{it
// 時分秒 this.TimeText.Text = DateTime.Now.ToString("HH:mm:ss");io
// 日期 農曆 5月1日 星期日
string MM = DateTime.Now.ToString("MM").TrimStart('0');
string dd = DateTime.Now.ToString("dd").TrimStart('0');
this.DateText.Text = "陽曆 ";
this.DateText.Text += MM;
this.DateText.Text += "月";
this.DateText.Text += dd;
this.DateText.Text += "日 ";
this.DateText.Text += DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("zh-cn"));
}
// 線程
System.Threading.Thread threadRead;
// 互斥鎖(看狀況使用)
object lockMe = new object();
threadRead = new System.Threading.Thread(threadReadFun);
threadRead.Start();
private void threadReadFun()
{
while (true)
{
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(0.5));
// 上鎖 lock (lockMe) { }
// 多線程中更新界面
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new delegate1(show));
}
}
// 上述線程中沒法對界面控件進行更新,可定義委託用於在多線程中更新界面
public delegate void delegate1();
private void show()
{
this.TextBlockName.Text = "new";
}
// 後臺操做控件,可經過查找Name
((Image)this.FindName("Image1")).Visibility = System.Windows.Visibility.Hidden;
// 多窗口關閉
// xaml
Closing="onClosing"
// cs
private void onClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
Environment.Exit(0);
}
// TextBox
GotFocus, LostFocus 得到和失去焦點事件,Tab得到焦點後使用 TextBox.SelectAll()選中全部內容 這對鍵盤從新輸入內容很方便
使用按鍵控制焦點移動:
private void keyDown(object sender, KeyEventArgs e) { UIElement element = Keyboard.FocusedElement as UIElement; if (e.Key == Key.A) { if (element != null) { element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous)); e.Handled = true; } } else if (e.Key == Key.D) { if (element != null) { element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); e.Handled = true; } } else if (e.Key == Key.W) { if (element != null) { element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Up)); e.Handled = true; } } else if (e.Key == Key.S) { if (element != null) { element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down)); e.Handled = true; } } else { return; } }