简体   繁体   中英

Draw or create databound UserControls dynamically at runtime in WPF

I'm trying to createa time-tracking application in WPF. The user is supposed to draw elements that represent a timespan (timespan = bar) onto a Canvas. Now, exisiting bars are added when they are databound to a collection (each collection item contains the width and left position of the bar on the Canvas).

The 'bar' Usercontrol has a dependency property called "ProjectProperty" which takes care of drawing and positioning the bar on the Canvas.

But what needs to happen when the user draws a new bar on the Canvas? It has to somehow be databound, but at what point in time does this need to happen, and how would I do that?

I understand that each of the 'bar' UserControls on the Canvas is databound, simply because they already exist in the datasource.

Say the user starts drawing the bar on mousedown and finishes on mouseup, do I have to programtically add its left position and width to the bound datasource? If not, how else would the datasource be updated?

Thanks!

The general approach I take when binding the View to a ViewModel, Model or Collection is to drive all changes from the Model/Collection up - so the view is purely listening and reflecting what it is bound to. So although you are tracking the mouse events in order to capture the position and size of the bar (and perhaps drawing a preview as the user is drawing), when the user completes the drawing operation you should add the new item to the underlying collection and let that bubble up to the View.

The pay off in my view for doing that routinely is that there is only one route through the code by which new items get added (directly to the datasource), and that reduces the code paths and potential for bugs / maintenance headaches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM