从Excel更新Runtime参数后,编辑框/单选按钮未同步显示新值
问题解决:Excel更新数据后UI控件未同步显示新值
核心原因
你的scenario所属的独立类没有实现属性变更通知机制,导致当Runtime属性值通过Excel读取更新后,UI控件无法感知到数据变化,因此仍显示旧值。
解决方案
1. 让数据类实现INotifyPropertyChanged接口
修改你的独立类,实现MVVM框架的标准属性通知接口,确保属性值变更时能通知UI刷新:
using System.ComponentModel; using System.Runtime.CompilerServices; public class Scenario : INotifyPropertyChanged { private int _runtime = 20; // 初始值 public int Runtime { get => _runtime; set { if (_runtime != value) { _runtime = value; OnPropertyChanged(); // 触发变更通知 } } } // 实现INotifyPropertyChanged接口 public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
2. 确认UI绑定配置正确
检查你的编辑框、单选按钮的绑定设置,确保:
- 控件的
DataContext已经正确指向scenario实例 - 绑定路径正确,比如编辑框的
Text属性绑定:{Binding Runtime, Mode=TwoWay}(需要双向同步时设置)
3. 非MVVM场景的替代方案(如WinForms)
如果是WinForms项目,无需实现INotifyPropertyChanged,可以在更新scenario.Runtime后手动刷新控件:
// 更新数据后手动同步UI txtRuntime.Text = scenario.Runtime.ToString(); // 单选按钮根据Runtime值设置选中状态,示例: radioBtnOption1.Checked = scenario.Runtime == 10; radioBtnOption2.Checked = scenario.Runtime == 20;
验证
修改完成后,重新执行Excel数据导入逻辑,此时scenario.Runtime更新时会自动触发UI控件刷新,显示最新值。
内容的提问来源于stack exchange,提问作者Aqeel Tariq
相关产品推荐
相关产品推荐

