Binding the position and size of a UserControl inside a Canvas in WPF

一个人想着一个人 提交于 2019-12-13 05:09:36

问题


We need to dynamically create (i.e. during runtime, via code-behind) UserControls and position them on a Canvas. We want to bind the position (Canvas.Left and Canvas.Top) and width of those sizable (!) and draggable (!) UserControls to a ObservableCollection<>. That measn when the user drags or resizes the control, the datasource gets automatically updated.

How would we achieve this if the Usercontrol is contained in a DataTemplate which in turn is used by a ListBox whose DataContext is set to the collection we want to bind to?

In other words, how do we bind a control's position and size that doesn't exist in XAML, but in code only (because it's created by clicking and dragging the mouse)?

Notice that the collection can be empty or not empty, meaning that the size and position stored in datasource must be correctly bound to so that the UserControl can be sized and positioned correctly in the Canvas - via DataBinding. Is this possible?


回答1:


Have you tried using a Mode=TwoWay binding?

<YourUserControl 
    Canvas.Top="{Binding TopProperty, Mode=TwoWay}" 
    Canvas.Left={Binding LeftProperty, Mode=TwoWay}" 
    Height="{Binding HeightProperty, Mode=TwoWay}" 
    Width="{Binding WidthProperty, Mode=TwoWay}" />

I'm not convinced two-way binding will work with resize or drag and drop operations, but there's only one way to find out.



来源:https://stackoverflow.com/questions/2545394/binding-the-position-and-size-of-a-usercontrol-inside-a-canvas-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!