nsg
nsg

Reputation: 10590

Programmatic data binding in WPF not working

I am working with two subclasses of FrameworkElement and trying to bind their widths and heights, so that when I set the Width or Height of one of the elements it updates the other element as well. Yet I'm setting something incorrectly with the bindings, as when I use Visual Studio's WPF Live Visual Tree to see the properties of the two FrameworkElements, I see that one has its Width and Height set correctly, while the other's is set to NAN. The code and snippets demonstrating the problem are below. What am I doing wrong?

Binding Source

Binding Source

Binding Target

Binding Target

Code to create binding

using System.Collections.Immutable;
using System.Windows;
using System.Windows.Data;
using Telerik.Windows.Controls.ChartView;

namespace CustomYAxis
{

    public class ChartYAxisAnnotation : CartesianCustomAnnotation
    {
        private readonly CustomYAxisView _annotationContent;

        public ChartYAxisAnnotation()
        {
            Content = _annotationContent = new CustomYAxisView();

            // These bindings aren't working
            var widthBinding = new Binding(nameof(WidthProperty))
            {
                Source = this,
            };

            var heightBinding = new Binding(nameof(HeightProperty))
            {
                Source = this
            };

            _annotationContent.SetBinding(WidthProperty, widthBinding);
            _annotationContent.SetBinding(HeightProperty, heightBinding);
        }
    }
}

Upvotes: 0

Views: 90

Answers (1)

PilouPili
PilouPili

Reputation: 2699

nameof(WidthProperty) actually returns "WidthProperty"

what you want to do is bind the property which name is "Width", same goes for HeightProperty

Therefore you should change nameof(WidthProperty) to WidthProperty.Name or "Width"

Upvotes: 1

Related Questions