实习期间开始使用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; } }