1、WPF前端控件绑定属性
<Grid>
<StackPanel Orientation="Vertical" Margin="20">
<StackPanel Orientation="Horizontal">
<TextBlock Text="重量:" FontSize="40"></TextBlock>
<TextBlock x:Name="NameWeight" Text="{Binding WeightData}" FontSize="40"></TextBlock>
</StackPanel>
<StackPanel Orientation="Vertical">
<Button Content="打开串口,获取重量" Width="300" HorizontalAlignment="Left" Click="Button_Click" FontSize="30"></Button>
</StackPanel>
</StackPanel>
</Grid>
2、MainWindow.xaml.cs
(1)实例化Test.cs类
(2)定义Button_click事件方法
public partial class MainWindow : Window
{
Test t = new Test();
public MainWindow()
{
InitializeComponent();
this.DataContext = t;
}
//绑定click事件
private void Button_Click(object sender, RoutedEventArgs e)
{
//调用
t.change();
}
}
3、Test.cs类
(1)继承WM类(已封装),用于实现属性改变后通知UI进行更新
(2)实例化串口对象sp1
(3)定义属性WeightData
(4)定义Button_click事件调用的change()方法,方法里边定义串口号、波特率、数据位、停止位等,调用sp1.Open()开启端口
(5)Sp1_DataReceived方法为串口数据获取算法,得到串口发送的数据(字节数组)后截取存为newByte新的字节数组,通过UTF8Encoding().GetString()讲字节数组解码为字符串,赋值给属性WeightData
private void Sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (sp1.IsOpen) //判断是否打开串口
{
Byte[] receivedData = new Byte[sp1.BytesToRead]; //创建接收字节数组
sp1.Read(receivedData, 0, receivedData.Length); //读取数据
int length = receivedData.Length;//计算出接收到的字节数组的长度
string head = ((int)receivedData[0]).ToString("X2") + ((int)receivedData[1]).ToString("X2");//获取字节数组头部;
//判断如果是数据头部分,则组装新字节数组的长度为6组
if (head == "0A0D")
{
string thirdBit = ((int)receivedData[2]).ToString("X2");//获取字节数组第三位的值
string fourthBit = ((int)receivedData[3]).ToString("X2");//获取字节数组第四位的值
int start = 2;//默认从第二组
string text1;
//如果第三组值为20,说明为空
if (thirdBit == "20")
{
len = 4;
start = 3;
for (int i = 0; i < len; i++)
{
int j = i + start;
newByte[i] = receivedData[j];
}
text1 = new UTF8Encoding().GetString(newByte, 0, 4);
text1 = text1.Substring(0, text1.Length - 3) + "." + text1.Substring(text1.Length - 3);
}
else
{
len = 5;
start = 2;
for (int i = 0; i < len; i++)
{
int j = i + start;
newByte[i] = receivedData[j];
}
text1 = new UTF8Encoding().GetString(newByte, 0, 5);
text1 = text1.Substring(0, text1.Length - 3) + "." + text1.Substring(text1.Length - 3);
}
WeightData = text1;
}
}
else
{
MessageBox.Show("请打开某个串口", "错误提示");
}
}
4、VM类
主要是对INotifyPropertyChanged的封装
public class VM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
public void RaiseAndSetIfChanged<T>(ref T a, T v, [CallerMemberName] string propertyName = null)
{
a = v;
if (propertyName != null)
{
RaisePropertyChanged(propertyName);
}
}
}