初学WPF,大体描述一下我的问题吧,我界面的一个ListView绑定了一个实现ObservableCollection的集合做数据源,在后台代码里用一个定时器每隔一定时间往该数据源添加一个对象元素,这样做导致界面没跟随数据源做变化,并且在拖动滚动条的时候,必然会抛出InvalidOperationException,描述信息为:An ItemsControl is inconsistent with its items source.
上代码~
public class TerminalCollection : ObservableCollection<TerminalInfo>
{
public void InsertTerminal(int count, TerminalInfo terminalInfo)
{
this.InsertItem(count, terminalInfo);
}
}
//给数据源定时添加元素的工具类
public class TerminalUtils
{
public static Mutex mutex = new Mutex();
public static TerminalCollection collection = new TerminalCollection();
public static void AddTerminals()
{
System.Timers.Timer timer = new System.Timers.Timer(2000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.AutoReset = true;
timer.Enabled = true;
}
public static void timer_Elapsed(object source, ElapsedEventArgs e)
{
mutex.WaitOne();
collection.InsertTerminal(collection.Count, GetOneTerminal()); //GetOneTerminal()为获取一个元素
mutex.ReleaseMutex();
}
}
public partial class MainWindow : DXRibbonWindow
{
public TerminalCollection observableObj;
public MainWindow()
{
InitializeComponent();
observableObj = TerminalUtils.collection;
}
//
public void bAddTerminals_Click(object sender, RoutedEventArgs e)
{
this.lv_User.DataContext = observableObj;
TerminalUtils.AddTerminals();
}
}
------解决思路----------------------
应该使用MVVM 模式
------解决思路----------------------
搞个MVVM,然后加上model=twoway试试
------解决思路----------------------
还不如写个OnPropertyChanged自己决定啥时候更新界面上的数据