首页 > 解决方案 > 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>

如果有人可以帮助我找出代码中的问题,将不胜感激。

标签: c#wpfmvvmdata-binding

解决方案


ItemsSource 具有类型ObservableCollection<string>,因此 ListBox 中的每个元素都是一个原始元素string

但是在 ItemTemplate 里面你有这个绑定:{Binding Path=Value}string没有Value属性,因此无法解析文本值并且不显示任何内容。

将绑定更改为{Binding Path=.}或简单地:{Binding}

调试提示:查看 Visual StudioOutput窗口 - IDE 报告错误的出价以及详细信息(如不存在的属性名称、类型不匹配等)


推荐阅读