How to bind an attached property in code to Canvas.Left or Canvas.Top?

I am trying to create a UserControl that can be dragged into a Canvas . I am new to MVVM and relatively new to WPF (also quite new to StackOverflow).

I have a view model that implements INotifyPropertyChanged for a new UserControl that has properties called "Top" and "Left". I would like to bind the Top and Left properties of my view model to the attached Canvas.Left and Canvas.Top the UserControl file. For reasons that I won’t fall into, I cannot use XAML .

Here's how I implemented my Left properties (and similarly to Top) (not sure how to do the work with code highlighting):

 public class FooViewModel : INotifyPropertyChanged { // . . . double _left; public double Left { get { return _left; } set { if(_left != value) { _left = value; NotifyPropertyChanged("Left"); } } } // . . . } 

This is how I implemented my "UserControl":

 public class FooControl : UserControl { // . . . private FooViewModel _vm; public FooControl(FooViewModel vm) { _vm = vm; this.DataContext = _vm; Binding b = new Binding("Left"); b.Mode = BindingMode.TwoWay; this.SetBinding(Canvas.LeftProperty, b); // . . . } // . . . } 

To check, I manually created some instances of the model, set the Left and Top properties on them, created instances of my UserControl , passing them to the constructor and adding them to the Canvas. Unfortunately, all my added controls are displayed in the upper left corner of the Canvas, and the debugger shows that if the Top and Left properties of the view model are set correctly by calling Canvas.GetLeft(...) and Canvas.GetTop(...) on the controls return NaN .

What am I doing wrong? Am I taking the wrong approach?

I tried to customize my code to this question and answer .

EDIT: Actually, it works! I made a mistake in my code where UserControl did not get the correct reference to the view model instance. As soon as I connected it correctly, it worked fine. Thanks everyone!

+4
source share
1 answer

This code should work fine.

Are controls actually the immediate children of the canvas? If not, this will not work.

+3
source

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


All Articles