开发者

Draw or create databound UserControls dynamically at runtime in WPF

开发者 https://www.devze.com 2022-12-25 01:10 出处:网络
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.

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 ha开发者_JAVA百科ve 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号