Binding UserControl position and size inside canvas in WPF

We need to dynamically create (i.e., at runtime, using the code) UserControls and place them on the canvas. We want to bind the position (Canvas.Left and Canvas.Top) and the width of these significant (!) And dragged (!) UserControls to the ObservableCollection <>. This is measured when the user drags or resizes the control; the data source is automatically updated.

How do 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 that we want to bind?

In other words, how do we snap the position and size of a control that does not exist in XAML, but only in the code (because it was created by clicking and dragging the mouse)?

Please note that the collection can be empty or empty, which means that the size and position stored in the data source must be properly linked so that UserControl can be correctly defined and positioned in the Canvas through the DataBinding. Is it possible?

0
source share
1 answer

Have you tried to use Mode=TwoWay ?

 <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 sure if two-way snapping will work with resize or drag options, but there is only one way to find out.

0
source

Source: https://habr.com/ru/post/1398150/


All Articles