【发布时间】:2022-01-15 17:09:02
【问题描述】:
我想将来自 VM 内的 TelemetryDataPoint 的数据显示到视图中,只是为了提供更多信息,TelemetryDataPoint 从我的 Helper 类接收数据。我已经尝试过使用下面的代码,但不知何故,数据不会显示在我的视图中,但如果我调试TelemetryDataPoint,它就会有值。
TelemetryDataPointVM.cs
public class TelemetryDataPointVM : INotifyPropertyChanged
{
private TelemetryDataPoint? telemetryDataPoint;
public TelemetryDataPoint? TelemetryDataPoint
{
get => telemetryDataPoint;
set
{
// when I checked the value below it has the value
telemetryDataPoint = value;
OnPropertyChanged(nameof(TelemetryDataPoint));
}
}
public TelemetryDataPointVM()
{
}
public event PropertyChangedEventHandler? PropertyChanged;
private void OnPropertyChanged(string propertyName)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
HelperClass.cs
public class GetPortHelper
{
TelemetryDataPointVM TelemetryDataPointVM { get; set; }
public GetPortHelper()
{
TelemetryDataPointVM = new();
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
if(sp.IsOpen)
{
string DataString = sp.ReadLine();
string[] arrayDataString = DataString.Split(",");
if(arrayDataString[3] == "C")
{
TelemetryDataPointVM.TelemetryDataPoint = ParseToTelemetryData(arrayDataString);
}
else if(arrayDataString[3] == "Y")
{
//ParseToTetheredData(arrayDataString);
}
}
}
}
Altitude.xaml
<UserControl x:Class="GUI_Cansat.View.Altitude"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:GUI_Cansat.View"
xmlns:vm="clr-namespace:GUI_Cansat.ViewModel"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.DataContext>
<vm:TelemetryDataPointVM/>
</UserControl.DataContext>
<Grid>
<Label Content="{Binding TelemetryDataPoint.Altitude, Mode=TwoWay}"
ContentStringFormat="Altitude: {0} M"
Style="{StaticResource fontMain}"
VerticalAlignment="Center" FontSize="14"/>
</Grid>
更新 1:
我将我的Altitude 组装到我的MainWindows 中,如下所示:
<Border Style="{StaticResource borderMain}"
Grid.Row="8">
<view:Altitude x:Name="Altitude" />
</Border>
我应该把DataContext 放在这个<view:Altitude/> 里面吗?如果我把这样的代码和{Binding TelemetryDataPointVM} 放在一起,我的 VS 会告诉我“找不到用于绑定的数据上下文”
【问题讨论】:
-
使用 Visual Studio 中的“XAML 绑定错误”窗口。你在里面看到什么? (在 VS 2019 v16.7 中添加,见这里:devblogs.microsoft.com/visualstudio/…)
-
Protip:在 C# 中使用
this.关键字,让阅读您的代码的人清楚识别标识符是否为实例成员。 -
您的属性
set逻辑应该只在属性值实际更改时调用OnPropertyChanged,现在您在调用 setter 时调用它:这是不正确的,并且可能导致无限-循环(例如,如果一个 setter 链接到另一个 setter)。 -
<vm:TelemetryDataPointVM/>GetPortHelper.TelemetryDataPointVM 属性中引用的实例不同。跨度> -
您好,感谢您的回复。我在选项下检查了
XAML Binding Errors,但我看不到那个设置(目前我正在使用VS 2022)@Dai