背景:从键盘获取数据 按照 enter 分为 epc 和 tid。
1 创建了一个 keydown 事件 但是发现 一打开窗体输入法会自动切换 于是我选择了禁用输入法:
复制代码
1
2在 xaml 中的 window 写: InputMethod.PreferredImeState="Off"
2 定义 keydown 事件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69private void Window_KeyDown(object sender, KeyEventArgs e) { string s = e.Key.ToString(); if(s.Length == 2) { string temp = s.Substring(1,1); str += temp; } else { str += s; } if(e.Key == Key.Enter) { if(k == 0) { epc = str; //----epc 局部变量 epc = epc.Substring(0,epc.Length - 6); //------去掉 return System.Diagnostics.Debug.WriteLine(epc); str = string.Empty; } if(k == 1) { tid = str; tid = tid.Substring(0,tid.Length - 6); System.Diagnostics.Debug.WriteLine(tid); str = string.Empty; //-----------数据处理 index += 1; //--------id 号 tags.Add(new Tags() // tags 集合类 下文有定义 { id = (index + 1).ToString(), Tid = tid, EPC = epc, result = getResult(epc) }); ((this.FindName("dataGrid") as DataGrid)).ItemsSource = tags; //-先赋值 否则更改不了背景颜色 if (!Window.GetWindow(dataGrid).IsVisible) { Window.GetWindow(dataGrid).Show(); } dataGrid.UpdateLayout(); //--------这段话必须定义 否则改颜色时报错显示空引用 if(getResult(epc) == "Success") { (dataGrid.Columns[3].GetCellContent(dataGrid.Items[index]) as TextBlock).Background=Brushes.Green; //-------改成绿色 } else { (dataGrid.Columns[3].GetCellContent(dataGrid.Items[index]) as TextBlock).Background = Brushes.Red; //------改成红色 } } if (k == 0) { k = 1; } else { k = 0; } } }
3 数据绑定
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
261 在主类的最上面定义如下: ObservableCollection<Tags> tags = new ObservableCollection<Tags>(); 2 在需要处理数据的地方 如本文是 keydown 中 对 tags 添加新的类 写法如下: tags.Add(new Tags() { id = (index + 1).ToString(), Tid = tid, EPC = epc, result = getResult(epc) }); 3 添加数据源 ((this.FindName("dataGrid")) as DataGrid).ItemsSource = tags; 4 在 xaml 文件中对数据进行绑定 本文的例子是 DataGrid <DataGrid.Columns> <DataGridTextColumn Header="id" Width="50" Binding="{Binding id}" FontFamily="微软雅黑" FontSize="20"/> <DataGridTextColumn Header="tid" Width="210" Binding="{Binding Tid}" FontFamily="微软雅黑" FontSize="20"/> <DataGridTextColumn Header="epc" Width="290" Binding="{Binding EPC}" FontFamily="微软雅黑" FontSize="20"/> <DataGridTextColumn Header="result" Width="260" Binding="{Binding result}" FontFamily="微软雅黑" FontSize="20"/> </DataGrid.Columns>
4 有关类的定义省略 有关 result 数据处理的关键定义省略。
最后
以上就是虚心紫菜最近收集整理的关于c# wpf 从设备读取 rfid 数据的全部内容,更多相关c#内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复