傲林 2021-11-15 16:16 采纳率: 83.3%
浏览 159
已结题

WPF如何动态绑定List<string>到ListBox

我声明了一个类用作数据的动态绑定,其中定义了一个string类型的list,想动态绑定到listbox或者其他控件,但在测试的时候发现添加成员到string集合无反应
这块我不是很懂,是绑定哪里出错了嘛

这是我用来动态绑定的类,其中的string类型集合

class BindingProperty : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));      
 
        private List<string> _readDataTextBlock = new List<string>;
 
        public List<string> ReadDataTextBlock 
        {
            get { return _readDataTextBlock; }
            set { _readDataTextBlock = value;OnPropertyChanged(nameof(ReadDataTextBlock)); }
        }
    }

这是后端调用的代码,我用“0000”做测试

public partial class MainWindow : Window
 {
        private BindingProperty _bindingProperty = new BindingProperty();
        public MainWindow()
        {
            this.DataContext = _bindingProperty;
            InitializeComponent();
        }
        private void ButtonReadByte_Click(object sender, RoutedEventArgs e)
        {
            _bindingProperty.ReadDataTextBlock.Add("0000");
        }
}

这是xaml里面的binding设置

<ListBox x:Name="ListBoxReadResult" Canvas.Left="93" Canvas.Top="30" Width="180" Height="144" Background="White" 
ItemsSource="{Binding Path=ReadDataTextBlock}"/>

点击click时监控string集合是有添加的,但是listbox始终无显示,如果在这基础上改如何改动最小

  • 写回答

1条回答 默认 最新

  • Admini$trat0r .net领域新星创作者 2021-11-15 16:21
    关注

    来帮助你了,这个list没有通知到UI
    可以试试换个数据结构
    比如bindinglist和observablecollection

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 11月23日
  • 已采纳回答 11月15日
  • 创建了问题 11月15日

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值