c# - MMVM Listbox 通过 MQTT 获取数据但不显示
问题描述
我有这个问题已经有一段时间了。我想通过 MQTT 接收一些数据并将这些消息显示在 ListBox 中。它可以在没有 MVVM 的情况下工作,但不能使用它。
发生的情况是数据被审查并传递给 ListBox。当我将鼠标悬停在 ListBox 上时,我可以看到有一些数据,因为它表明可以显示一个项目。
我的代码如下:
看法
public partial class ShellView : Window
{
public ShellView()
{
InitializeComponent();
this.DataContext = new ShellViewModel();
}
}
视图模型
ObservableCollection<string> _data = new ObservableCollection<string>();
public ObservableCollection<string> Data
{
get
{
return _data;
}
set {
_data = value;
RaisePropertyChanged("Data");
}
}
#region INotifyPrortyChanged
public const string propertyName = "Data";
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
我怀疑错误的 ViewModel 的一部分
private void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
Application.Current.Dispatcher.Invoke((Action)delegate
{
_data.Add(Encoding.UTF8.GetString(e.Message));
});
foreach (string o in _data.ToList())
{
//MessageBox.Show(o); shows that the string "json" is recieved
Application.Current.Dispatcher.Invoke((Action)delegate
{
//MessageBox.Show(o); same here
Data.Add(o);
});
}
}
视图.Xaml
ListBox x:Name="lBox" ItemsSource="{Binding Data}" Background="White" Grid.Column="1" Margin="192,52,134,10" BorderBrush="Black" BorderThickness="2" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Value}" Background="red"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
如果有人可以帮助我找出代码中的问题,将不胜感激。
解决方案
ItemsSource 具有类型ObservableCollection<string>
,因此 ListBox 中的每个元素都是一个原始元素string
。
但是在 ItemTemplate 里面你有这个绑定:{Binding Path=Value}
。string
没有Value
属性,因此无法解析文本值并且不显示任何内容。
将绑定更改为{Binding Path=.}
或简单地:{Binding}
调试提示:查看 Visual StudioOutput
窗口 - IDE 报告错误的出价以及详细信息(如不存在的属性名称、类型不匹配等)
推荐阅读
- scala - 无法将多个流合并为一个
- c - 指针的垃圾数据
- python - 即使我使用“super()”,我是否需要手动将属性从超类的“__init__”传递到子类的“__init__”?
- python - 如何在 Flask 中增加我的查看计数器?
- responsive-design - Foundation 在小屏幕上显示尺寸
- javascript - Daily Countdown Timer for Shipping hours
- sqlite - 在另一张桌子上查找最长的匹配号码
- mongodb - 使用验证规则更新 mongodb 集合时如何禁止未知属性?
- angular - 带有 Angular 7 的微型应用程序 - Zone.js 和自定义元素问题
- amazon-web-services - AWS ECS - Can't connect to RabbitMQ EC2 instance from ECS container instance on the same subnet