c# - How to keep my selection to the DataGrid Row after refresh the data grid using timer in WPF -
i have wpf datagrid , binding datagrid if changes made data automatically refresh selection datagrid row unselected.
instead of using list
store data, try using observablecollection
. advantage of using observablecollection
whenever add item collection ui automatically updated manually refresh of datagrid
not required. below have shared sample application adds , updates record in datagrid
.
xaml:
<grid> <grid.rowdefinitions> <rowdefinition height="auto"/> <rowdefinition height="auto"/> </grid.rowdefinitions> <stackpanel orientation="horizontal"> <radiobutton name="cbadd" groupname="addoredit" content="add messages" ischecked="true"></radiobutton> <radiobutton name="cbupdate" groupname="addoredit" content="update messages"></radiobutton> </stackpanel> <datagrid grid.row="1" name="dgnew" canuseraddrows="false"> </datagrid> </grid>
code behind:
using system; using system.windows; using system.timers; using system.collections.objectmodel; using system.windows.threading; using system.componentmodel; namespace wpfapplication1 { /// <summary> /// interaction logic mainwindow.xaml /// </summary> public partial class mainwindow : window { timer _timer = null; observablecollection<custommessage> _messages = null; int count = 0; public mainwindow() { initializecomponent(); _messages = new observablecollection<custommessage>(); count++; _messages.add(new custommessage() { id = count, message = "message" }); _timer = new timer(1000); _timer.elapsed += new elapsedeventhandler(_timer_elapsed); this.dgnew.itemssource = _messages; _timer.start(); } void _timer_elapsed(object sender, elapsedeventargs e) { try { _timer.stop(); application.current.dispatcher.invoke(dispatcherpriority.background, new action(() => { if (this.cbadd.ischecked == true) { count++; _messages.add(new custommessage() { id = count, message = "timer message " + count }); } else { // udpate existing message random random = new random(); custommessage message = _messages[random.next(0, count)]; message.message = "updated time" + datetime.now.tolongtimestring(); } })); } { _timer.start(); } } } public class custommessage : inotifypropertychanged { private int _id; public int id { { return _id; } set { _id = value; onpropertychanged("id"); } } private string _message; public string message { { return _message; } set { _message = value; onpropertychanged("message"); } } public event propertychangedeventhandler propertychanged; public void onpropertychanged(string propertyname) { if (propertychanged != null) propertychanged(this, new propertychangedeventargs(propertyname)); } } }
Comments
Post a Comment