WPF使用小技巧

3 篇文章 0 订阅
一.窗体居中设定
this.WindowStartupLocation = WindowStartupLocation.CenterScreen; // 可以使当前窗体居中。
二. 动态更新WPF不同名字的控件Text
TextBlock bTested = this.FindName("bin" + (i).ToString() + "Tested") as TextBlock; // 根据名字定位到具体的block控件对象
bTested.Text = "赋值"; // 直接赋值
三.判断字符串是否相等
string.Equals("1", res5) //判断是否"1"和res的内容是否相等,相等的话返回true
四.多线程使用控件,需要使用异步操作,不然会报错
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, new System.Action(() =>{
		//这里面是操作控件的代码
		// 比如
		// testBlock 是 TextBlock的Name
		testBlock.Text = "测试测试"
}));
五.WPF中开启定时器
第一步:创建定时器对象
		//创建对象
        private DispatcherTimer timer;
        void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                //实例化对象
                timer = new DispatcherTimer();
                //设置触发时间 5000ms
                timer.Interval = TimeSpan.FromMilliseconds(testTempTime);
                //设置触发事件
                timer.Tick += timer1_Tick; // timer1_Tick为触发之后的函数,时间间隔为5000ms
                //启动
                timer.Start();
            }
            catch
            {
                MessageBox.Show("错误", "ERROR");
            }

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try {
                //(定时处理的事情) 发送请求报文,获取温度,渲染WPF界面
                // .........
            } catch
            {
                
            }
             
        }
第二步:在window_Load添加。
		/// <summary>
        /// 主窗口
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(Window1_Loaded);
            // 初始化数据
            initData();
        }
六.判断字符串是否是null或者为空
string.IsNullOrEmpty(p_number)  // p_number是string变量

七.获取启动项目实际的路径
string appStartupPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

八.清空richtext
richLog.Document.Blocks.Clear();
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值