wpf绑定模板时没更新UI 原因:不要用clear()要用new,为什么呢?谁会想到这个坑?

 绑定模板时没更新UI。不要用clear()要用new。

 bindingListSP = new List<BindingClass>();//bindingListSP.Clear();不行

using FT_Tools;
using MSFramework.Common;
using NFC_Help;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Management;
using System.Windows;
using WpfDownloadTool;
using static System.Net.Mime.MediaTypeNames;

namespace WpfM20UpdateFW
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        //把串口按插入的顺序排序,同时插不考虑。增加新的 删不存在
        List<string> comListSP = new List<string>();
        List<string> comListAP = new List<string>();
        public USB USBWatcher = new USB();
        private List<DownloadSP1902QualComm> dList = new List<DownloadSP1902QualComm>();
        List<BindingClass> bindingListSP = new List<BindingClass>();
        List<BindingClass> bindingListAP = new List<BindingClass>();
        private int AutoTask =1;
        private int mode = 1;
        private int MaxDeviceCount = 8;
        private int Speech = 1;
        public MainWindow()
        {
            InitializeComponent();
            this.Title +=  System.IO.File.GetLastWriteTime(this.GetType().Assembly.Location);

            init();
            setDownloadList();
            USBWatcher.AddUSBEventWatcher(USBEventHandler, USBEventHandler, new TimeSpan(0, 0, 1));
        }
        public void init()
        {
            logText.Text = "";
            bindingListSP = new List<BindingClass>();//bindingListSP.Clear();不行
            bindingListAP = new List<BindingClass>(); //bindingListAP.Clear();
            DownloadSP1902QualComm.SP = IniFile.GetPrivateProfileInt(DownloadSP1902QualComm.configAppName, "SP", 1, IniFile.m_FileName);
            DownloadSP1902QualComm.AP = IniFile.GetPrivateProfileInt(DownloadSP1902QualComm.configAppName, "AP", 1, IniFile.m_FileName);
            DownloadSP1902QualComm.timeoutSecond = IniFile.GetPrivateProfileInt(DownloadSP1902QualComm.configAppName, "TimeoutSecond", 20, IniFile.m_FileName);
            DownloadSP1902QualComm.SP_SigFile = IniFile.ReadString(DownloadSP1902QualComm.configAppName, DownloadSP1902QualComm.SigFilePath, ""); //资源号或本地文件名
            DownloadSP1902QualComm.SP_RSAKeyFile = IniFile.ReadString(DownloadSP1902QualComm.configAppName, DownloadSP1902QualComm.RSAKeyPath, ""); //资源号或本地文件名
            DownloadSP1902QualComm.AP_File = IniFile.ReadString(DownloadSP1902QualComm.configAppName, DownloadSP1902QualComm.APPath, "");
            DownloadSP1902QualComm.AutoComCount = IniFile.GetPrivateProfileInt(DownloadSP1902QualComm.configAppName, "AutoComCount", 1, IniFile.m_FileName);
            AutoTask = IniFile.GetPrivateProfileInt(DownloadSP1902QualComm.configAppName, "AutoTask", 1, IniFile.m_FileName);
            MaxDeviceCount = IniFile.GetPrivateProfileInt(DownloadSP1902QualComm.configAppName, "MaxDeviceCount", 8, IniFile.m_FileName);
            Speech=IniFile.GetPrivateProfileInt(DownloadSP1902QualComm.configAppName, "Speech", 1, IniFile.m_FileName);
            mode = IniFile.GetPrivateProfileInt(DownloadSP1902QualComm.configAppName, "mode", 1, IniFile.m_FileName);
            Log("MaxDeviceCount=" + MaxDeviceCount);
            Log("AutoCom=" + DownloadSP1902QualComm.AutoComCount);
            Log("SP=" + DownloadSP1902QualComm.SP);
            Log("AP=" + DownloadSP1902QualComm.AP);
            Log("SP_SigFile=" + DownloadSP1902QualComm.SP_SigFile);
            Log("SP_RSAKeyFile=" + DownloadSP1902QualComm.SP_RSAKeyFile);
            Log("AP_File=" + DownloadSP1902QualComm.AP_File);
            //设置进度条 界面更新
            for (int i = 0; i < MaxDeviceCount; i++)
            {
                bindingListSP.Add(new BindingClass() { Name = IniFile.ReadString(DownloadSP1902QualComm.configAppName, "SP_COM" + (i + 1), "" + (i + 1)) });
                bindingListAP.Add(new BindingClass() { Name = IniFile.ReadString(DownloadSP1902QualComm.configAppName, "AP_COM" + (i + 1), "" + (i + 11)) });
            }
            myListBoxSP.ItemsSource = bindingListSP;
            myListBoxAP.ItemsSource = bindingListAP;


            //加载任务
            dList.Clear();
            for (int i = 0; i < bindingListSP.Count; i++)
            {
                dList.Add(new DownloadSP1902QualComm(Log, bindingListSP[i].Name, bindingListAP[i].Name, i));
                dList[i].OnUpdateUI += OnUpdateUI;
            }
        }

        private void USBEventHandler(Object sender, EventArrivedEventArgs e)
        {
            //暂未实现
            var watcher = sender as ManagementEventWatcher;
            watcher.Stop();
            //刷新设备信息
            if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
            {
                Log("Device Arrived");
                setDownloadList();
                SaveCom();//只在插入时保存
            }
            else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent")
            {
                Log("Device Removed");
                setDownloadList();              
            }
            // 业务代码,逻辑耗时尽量不要太长,以免影响事件的监听
            watcher.Start();
        }

        private void AutoTaskDownlaod()
        {
            if (AutoTask == 1&& DownloadSP1902QualComm.SP > 0 && DownloadSP1902QualComm.AP>0)
            {
                for (int i = 0; i < bindingListAP.Count; i++)
                {
                    if (!MySerialPort.isComExist(Log, bindingListAP[i].Name))
                    {
                        if (bindingListAP[i].ProgressValue == 100)
                        {
                            Dispatcher.Invoke((Action)(() => {  logText.Text = "";  }));//清空还原
                            if (dList[i].thread_isRunning == false)
                            {
                                Log("AutoTask "+(i+1));
                                dList[i].Start();
                            }           
                        }
                    }
                }
            }
        }

        private void AutoSortCom(List<string> comList,ref List<string> sortList)
        {
            try
            {
                if (comList.Count == 0) { sortList.Clear(); return; }
                foreach (string com in comList)
                {
                    if (!sortList.Contains(com)) //增加新的
                    {
                        sortList.Add(com);
                    }
                }
                for (int i = 0; i < sortList.Count;)
                {
                    if (!comList.Contains(sortList[i])) //删不存在
                    {
                        sortList.Remove(sortList[i]);
                    }
                    else
                    {
                        i++;
                    }
                }
            }
            catch (Exception e) {
                Log(e.StackTrace);
            }
    
        }
        //根据串口数量显示进度条数量
        private void setDownloadList()
        {
            AutoSortCom(DownloadSP1902QualComm.GetComNameListSP(Log), ref comListSP);//有几个设备显示几个显示条
            if (comListSP.Count <= DownloadSP1902QualComm.AutoComCount)
            {
                for (int i = 0; i < comListSP.Count; i++)
                {                  
                    if (dList.Count > 0) {  dList[i].spCom = comListSP[i]; }
                    if (bindingListAP.Count > i) { bindingListSP[i].Name = comListSP[i];  }//刷新一下
                }
            }

            AutoSortCom(DownloadSP1902QualComm.GetComNameListAP(Log), ref comListAP);//有几个设备显示几个显示条
            //Log("AutoComCount=" + AutoComCount);
            if (comListAP.Count <= DownloadSP1902QualComm.AutoComCount) //只一个时有效
            {
                for (int i = 0; i < comListAP.Count; i++)
                {
                    if (dList.Count > 0) { dList[i].apCom = comListAP[i]; }
                    if (bindingListAP.Count > i) { bindingListAP[i].Name = comListAP[i]; }//刷新一下
                    //Log(i+" "+bindingListAP[i].Name+"  "+ comListAP[i]);
                }
            }
            Log("SP quantity:" + comListSP.Count+ " AP quantity:" + comListAP.Count);
        }
        private void SaveCom()
        {
            if (comListAP.Count == DownloadSP1902QualComm.AutoComCount)//所有设备都插上了,保存
            {
                for (int i = 0; i < comListSP.Count; i++)
                {
                    IniFile.WriteString(DownloadSP1902QualComm.configAppName, "SP_COM" + (i + 1), comListSP[i]);                   
                }
                for (int i = 0; i < comListAP.Count; i++)
                {
                    IniFile.WriteString(DownloadSP1902QualComm.configAppName, "AP_COM" + (i + 1), comListAP[i]);
                }
                Log("Save com success");
            }
        }
     
        
        private void Log(string log)
        {
      
            //Dispatcher.BeginInvoke((Action)(() => { //异步
            Dispatcher.Invoke((Action)(() => {      //同步
                try
                {
                    MyLog.MyLog.WriteLogs(MyLog.MyLog.fileName, "", log);
                    if (mode == 1 && logText.Text.Length > 5000)
                    {
                        logText.Text = "";
                        //logText.Text = logText.Text.Substring(logText.Text.Length - 100); //clear
                    }
                    logText.Text += log + "\r\n";
                    //logText.SelectionStart = logText.Text.Length;
                    logText.ScrollToEnd();
                }
                catch { }
            }));
        }
        private void Window_Closed(object sender, EventArgs e)
        {
            if (dList != null)
            {
                foreach (var d in dList)
                {
                    d.Stop();
                }
            }
            MyAPI.killProcess("ISPGui");
        }

        private void Button_Click_ap(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new Microsoft.Win32.OpenFileDialog()
            {
                Filter = "F200 F600 AP|*.mbn|F100 AP|*.txt|F200-A F210 AP|*.pac",
                Multiselect = false
            };
            if (openFileDialog.ShowDialog()==true)
            {
                Log("AP_File=" + openFileDialog.FileName);
                IniFile.WritePrivateProfileString(DownloadSP1902QualComm.configAppName, DownloadSP1902QualComm.APPath, DownloadSP1902QualComm.AP_File = openFileDialog.FileName, IniFile.m_FileName);
            }
        }

        private void Button_Click_sp_sig(object sender, RoutedEventArgs e)
        {
            //运行时不能修改
            for (int i = 0; i < bindingListSP.Count; i++)
            {
                if (dList[i].thread_isRunning == true)
                {
                    Log("There are unfinished tasks that cannot be edited.");
                    return;
                }
            }
            SettingsWindow window = new SettingsWindow();
            bool? b = window.ShowDialog();
            init(); //重新


            //var openFileDialog = new Microsoft.Win32.OpenFileDialog()
            //{
            //    Filter = "SP File|*.SIG|F100 SP|*.hex",
            //    Multiselect = false
            //};
            //if (openFileDialog.ShowDialog() == true)
            //{
            //    Log("SP_SigFile=" + openFileDialog.FileName);
            //    IniFile.WritePrivateProfileString(DownloadSP1902QualComm.configAppName, DownloadSP1902QualComm.SigFilePath, DownloadSP1902QualComm.SP_SigFile = openFileDialog.FileName, IniFile.m_FileName);
            //}

            //文件夹
            //var dialog = new System.Windows.Forms.FolderBrowserDialog()
            //{
            //    Description = "Please select SP File path"
            //};

            //if(  dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //    Log("SP_SigFile=" + dialog.SelectedPath);
            //    IniFile.WritePrivateProfileString(configAppName, SigFilePath, SP_SigFile = dialog.SelectedPath, IniFile.m_FileName);
            //}
        }
        private void Button_Click_sp_rsa(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new Microsoft.Win32.OpenFileDialog()
            {
                Filter = "SP File|*.RSA",
                Multiselect = false
            };
            if (openFileDialog.ShowDialog() == true)
            {
                Log("SP_RSAKeyFile=" + openFileDialog.FileName);
                IniFile.WritePrivateProfileString(DownloadSP1902QualComm.configAppName, DownloadSP1902QualComm.RSAKeyPath, DownloadSP1902QualComm.SP_RSAKeyFile = openFileDialog.FileName, IniFile.m_FileName);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            download.IsEnabled = false;
            MyAPI.speech(download.Content.ToString(), Speech);
            logText.Text = ""; //清空还原
            for (int i = 0; i < bindingListSP.Count; i++)
            {
                if (dList[i].thread_isRunning == false)
                {
                    dList[i].Start();
                }
            }
        }


        private void Window_Loaded(object sender, RoutedEventArgs e2)
        {
      
        }

        private void OnUpdateUI(MessageType type, int index, int value, bool result)
        {
            if (type == MessageType.SP_Progress)
            {              
                if (value == 0)
                {
                    bindingListSP[index].ProgressValue = value;
                    bindingListSP[index].ProgressForeground = System.Windows.Media.Brushes.CornflowerBlue;
                }
                else if (value == 100)
                {
                    bindingListSP[index].ProgressValue = value;
                    bindingListSP[index].ProgressForeground = (result ? System.Windows.Media.Brushes.Green : System.Windows.Media.Brushes.Red);
                }
                else {
                    if (bindingListSP[index].ProgressValue > 90) { bindingListSP[index].ProgressValue = 50; } else { bindingListSP[index].ProgressValue++; }
                }
            }
            else if (type == MessageType.AP_Progress)
            {

                if (value == 0)
                {
                    bindingListAP[index].ProgressValue = value;
                    bindingListAP[index].ProgressForeground = System.Windows.Media.Brushes.CornflowerBlue;
                }
                else if (value == 100)
                {
      
                    bindingListAP[index].ProgressValue = value;            
                    bindingListAP[index].ProgressForeground = (result ? System.Windows.Media.Brushes.Green : System.Windows.Media.Brushes.Red);
                }
                else
                {
                    if (bindingListAP[index].ProgressValue > 90) { bindingListAP[index].ProgressValue = 50; } else { bindingListAP[index].ProgressValue++; }
                }
            }
            else if (type == MessageType.FINISH)
            {
                Dispatcher.Invoke((Action)(() => { download.IsEnabled = true; }));
                MyAPI.speech((1 + index) + (result ? " Pass" : " Fail"), Speech);
            }
        }
    }
    public class DownloadProgress
    {
        public string Name { get; set; }//串口
    }
}

绑定的变量 更新需要,set时调用属性变动事件

using System.ComponentModel;
using System.Windows.Media;

namespace WpfDownloadTool
{
    //用于变量同步更新界面上的信息
    public class BindingClass : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, e);
        }



        private string _Name;   //进度条上显示串口号等
        public string Name
        {
            get { return _Name; }
            set
            {
                if (value != _Name)
                {
                    _Name = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("Name")); //是绑定的变量Path名 <Binding Path="Name"/>
                }
            }
        }

        private int _ProgressValue;  //进度条值
        public int ProgressValue
        {
            get { return _ProgressValue; }
            set
            {
                if (value != _ProgressValue)
                {
                    _ProgressValue = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("ProgressValue"));// not ProgressBar Name
                }
            }
        }
        private Brush _ProgressForeground;  //进度条颜色
        public Brush ProgressForeground
        {
            get { return _ProgressForeground; }
            set
            {
                if (value != _ProgressForeground)
                {
                    _ProgressForeground = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("ProgressForeground"));// not ProgressBar Name
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
当使用数据绑定WPF 会自动处理数据更改并更新界面,但是在某些情况下可能会出现界面更新有延迟的情况。这可能是因为 WPF 在处理大量数据或在 UI 线程上执行长间操作可能会出现性能问题。 以下是一些可能导致界面更新延迟的原因: 1. 数据量过大:如果你绑定的数据集非常大,WPF 可能需要花费大量间来更新界面。在这种情况下,你可以使用虚拟化技术,例如使用虚拟化面板或仅加载可见项的数据。 2. 长间操作:如果你在 UI 线程上执行长间操作,例如在数据更改事件处理程序中进行复杂计算或网络请求,WPF 可能无法及更新界面。在这种情况下,你可以考虑将操作移到后台线程中执行,或者使用异步方法并在其完成更新界面。 3. 控件样式过于复杂:如果你的控件样式过于复杂,例如使用复杂的模板或窗口效果,WPF 可能需要花费大量间来更新界面。在这种情况下,你可以考虑简化控件样式,或使用基于硬件加速的效果。 4. 数据绑定周期:当绑定的数据发送更改通知,数据绑定会在下一个 UI 帧中更新界面。如果你的数据更改非常频繁,可能会导致界面更新有延迟。在这种情况下,你可以使用 `UpdateSourceTrigger` 属性将数据绑定更新模式更改为 `PropertyChanged`,以实现即更新。 希望这些提示能帮助你解决界面更新延迟的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小黄人软件

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值