简体   繁体   English

在WPF中在运行时动态绘制或创建数据绑定的UserControl

[英]Draw or create databound UserControls dynamically at runtime in WPF

I'm trying to createa time-tracking application in WPF. 我正在尝试在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. “ bar”用户控件具有一个名为“ ProjectProperty”的依赖项属性,该属性负责在Canvas上绘制和放置bar。

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. 我知道Canvas上的每个“ bar” UserControl都是数据绑定的,仅仅是因为它们已经存在于数据源中。

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? 假设用户在mousedown上开始绘制该条,而在mouseup上完成,我是否需要以编程方式将其左侧位置和宽度添加到绑定的数据源中? 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. 将View绑定到ViewModel,Model或Collection时,我采用的一般方法是推动Model / Collection中的所有更改-因此,视图纯粹是在侦听并反映其绑定的内容。 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. 因此,尽管您正在跟踪鼠标事件以捕获条的位置和大小(并可能在用户绘图时绘制预览),但是当用户完成绘图操作时,应将新项目添加到基础集合中,然后让气泡上升到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. 在我看来,定期执行此操作的好处是,只有一条通过代码的路径可以添加新项(直接添加到数据源),这减少了代码路径并减少了错误/维护麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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