serhio
serhio

Reputation: 28586

Bind to a property

I have an object(class): Foo.

It has a property: Bar.

What should I do to be able to Bind to that 'Bar' property?

(WPF, .NET 4)

EDIT:

TO be more explicit, I give an example:

I have a Dot:UserControl

I create 2 properties of Dot - CenterX and CenterY:

    public double CenterX
    {
        get
        {
            return Canvas.GetLeft(this) + this.Width / 2;
        }
        set
        {
            Canvas.SetLeft(this, value - this.Width / 2);
        }
    }

    public double CenterY
    {
        get
        {
            return Canvas.GetTop(this) + this.Height / 2;
        }
        set
        {
            Canvas.SetLeft(this, value - this.Height / 2);
        }
    }

Now:

<Line Stroke="Black" x:Name="line1"
      X1="{Binding ElementName=dot1, Path=CenterX}"
      Y1="{Binding ElementName=dot1, Path=CenterY}"

      X2="{Binding ElementName=dot2, Path=CenterX}"
      Y2="{Binding ElementName=dot2, Path=CenterY}" />

does not work...

Upvotes: 0

Views: 188

Answers (2)

SKG
SKG

Reputation: 1462

Implement INotifyPropertyChanged to your Class so that WPF binding framework will know to update the relevant bound controls when the property has been changed.

For the actual binding, you might find this useful

http://japikse.blogspot.com/2009/07/inotifypropertychanged-and-wpf.html

With INotifyPropertyChanged you class will look like

 public class Foo:INotifyPropertyChanged
    {
        public double CenterX
        {
            get
            {
                return Canvas.GetLeft(this) + this.Width / 2;
            }
            set
            {
                Canvas.SetLeft(this, value - this.Width / 2);
                OnPropertyChanged("CenterX");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

Anytime CenterX value is changed, the OnPropertyChanged("CenterX"); will tell the UI to refresh controls which have properties bound to it

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292675

Your question isn't precise enough to answer it completely... Unless specified otherwise, binding paths are always relative to the control's DataContext. Assuming your DataContext is an instance of Foo, you can do that:

<TextBlock Text="{Binding Bar}" />

Or if you want to be more explicit:

<TextBlock Text="{Binding Path=Bar}" />

Now, if Foo is itself a property of the current DataContext, you can do that:

<TextBlock Text="{Binding Foo.Bar}" />

Have a look at this Binding Cheat Sheet, it's very helpful when you're new to WPF binding

Upvotes: 0

Related Questions