WFP Listbox绑定数据后,数据变化的刷新

Listbox绑定数据通过ItemsSource来的,如果绑定的是普通的List<数据>,不会自己刷新。

使用ObservableCollection集合

解决问题的方法:

  1. 将数组替换为 ObservableCollection
    ObservableCollection 是专为绑定设计的集合类型,可以通知 WPF 绑定的集合数据发生变化。

如果本身是List,可以修改为:

csharp 复制代码
using System.Collections.ObjectModel;

public ObservableCollection<MyItem> MyItems { get; set; }

public MainViewModel()
{
    MyItems = new ObservableCollection<MyItem>
    {
        new MyItem { showsafeui = true, SomeOtherProperty = "Item 1" },
        new MyItem { showsafeui = false, SomeOtherProperty = "Item 2" },
        new MyItem { showsafeui = true, SomeOtherProperty = "Item 3" }
    };
}

// 动态添加或删除数据
public void AddNewItem()
{
    MyItems.Add(new MyItem { showsafeui = true, SomeOtherProperty = "New Item" });
}

public void RemoveItem()
{
    if (MyItems.Any())
        MyItems.RemoveAt(0);
}

使用 ObservableCollection 后,新增、删除、或重新排序数据时,ListBox 会自动刷新。

数据内容变化的刷新INotifyPropertyChanged

上面的数据,如果某个属性的内容发生了变化如何刷新。可以使用INotifyPropertyChanged。

csharp 复制代码
public class HeartInfo : INotifyPropertyChanged
{
    public int id { get; set; }
    public bool showsafeui{ get; set; }
    
	public event PropertyChangedEventHandler PropertyChanged;
	protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
	{
	    Console.WriteLine("刷新UI------------");
	    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
	}
}

刷新单个数据

这样在某个属性变化的时候,可以

csharp 复制代码
	public bool showsafeui
    {
        get => _showsafeui;
        set
        {
            if (_showsafeui != value)
            {
                _showsafeui = value;
                OnPropertyChanged(); // 通知绑定属性更改
            }
        }
    }

刷新多个数据

如果某个属性变化需要刷新多个

csharp 复制代码
	private bool _showsafe;

    public bool showsafe
    {
        get => _showsafe;
        set
        {
            if (_showsafe != value)
            {
                _showsafe = value;
                OnPropertyChanged(); // 通知绑定的 showsafe 属性
                OnPropertyChanged(nameof(showsafeui)); // 通知绑定的 showsafeui 属性
            }
        }
    }

简化刷新所有

我每次都想有一个属性变化,刷新所有属性

可以OnPropertyChanged(string.Empty)传入空

csharp 复制代码
	private int _updateall  = 0;
	public int updateall 
	{
    	get { 
    	return _updateuistat;
    }
    set {
        if (_updateall!= value) { 
            _updateall= 0; 
            OnPropertyChanged(string.Empty); 
        }
    }  //刷新ui
}

这样我每次属性变化都调用updateall = 1,就全部刷新了。

相关推荐
✎ ﹏梦醒͜ღ҉繁华落℘3 小时前
开发WPF项目时遇到的问题总结
wpf
hqwest1 天前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
Vae_Mars1 天前
WPF中使用InputBindings进行快捷键绑定
wpf
hqwest1 天前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
hqwest1 天前
C#WPF实战出真汁01--项目介绍
开发语言·c#·wpf
wuty0072 天前
WPF 实现支持动态调整高度的文本显示控件
wpf·scrollviewer·extentheight·自动高度控件·动态调整高度
范纹杉想快点毕业5 天前
C 语言主控开发与显控开发能力体系及技术栈详解,STM32、QT、嵌入式、边缘系统显示
stm32·单片机·tcp/ip·microsoft·fpga开发·51单片机·wpf
weixin_447103585 天前
WPF之绑定!
c#·wpf
DataIntel5 天前
wpf问题记录
wpf
蓝点lilac7 天前
C# WPF 内置解码器实现 GIF 动图控件
c#·.net·wpf·图像