简体   繁体   中英

Dependency property Canvas not binding

I'm making a tool where I can edit images, so I have a custom Control to draw on a canvas. For this control I bound the resolution and the color of the brush which work perfectly fine, but when I try to bind a Canvas I always get null in myViewModel.

I tried binding a List instead, but that didn't work either. I've been trying to figure out what the problem is for about 12 hours now so I think it's time to ask you guys for help so I can maybe figure out what's wrong.

I used to work with singletons for my viewmodels, and then I could link to the Canvas just fine, but then I realised this is a bad way of working so I tried to bind it with dependency properties.

Whenever I try to access the Canvas it has a value of null, even though I initialized it.

Control

    public static readonly DependencyProperty CanvasProperty = DependencyProperty.Register(
  "CanvasToDraw", typeof(Canvas), typeof(DrawCanvas), new PropertyMetadata(default(Canvas), null, null));

    public Canvas CanvasToDraw
    {
        get { return (Canvas)GetValue(CanvasProperty); }
        set { SetValue(CanvasProperty, value); }
    }

        public DrawCanvas()
    {
        InitializeComponent();
        CanvasToDraw = CanvasGrid;
    }

XAML

<Controls:DrawCanvas x:Name="DrawCanvas1" Resolution="{Binding Resolution}" CanvasToDraw="{Binding DrawingCanvas}" RectangleList="{Binding RectangleList, ElementName=DrawCanvas1}" ColorToDraw="{Binding SelectedColor}" HorizontalAlignment="Left" Height="256" Margin="10,40,0,0" VerticalAlignment="Top" Width="256" />

VIEWMODEL

        private Canvas _drawingCanvas;
    public Canvas DrawingCanvas
    {
        get { return _drawingCanvas; }
        set
        {
            _drawingCanvas = value;
            OnPropertyChanged("DrawingCanvas");
        }
    }

I can provide more code if needed, but this is most of the relevant code. And yes I do use INotifyPropertyChanged, since I have other things that I bound that do work.

I've been looking for a solution for so long, but the answer was so simple. I assumed the binding was two way, but appareantly I had to set Mode=TwoWay and everything worked like a charm. (Linking an observeablecollection, not a Canvas)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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