Ahmed Ghoneim
Ahmed Ghoneim

Reputation: 7067

Binding Problem

XAML

<TextBlock Grid.Column="1"
                   Height="37"
                   Margin="8,17,0,0"
                   HorizontalAlignment="Left"
                   VerticalAlignment="Top"
                   FontSize="20"
                   Text="{Binding Contact.Name,
                                  UpdateSourceTrigger=PropertyChanged}" />

C# Code behind XAML

public partial class Conversation : Window
{

    private Friend _Contact;
    public Friend Contact
    {
        get
        {
            return _Contact;
        }
        set
        {
            _Contact = value;
            OnPropertyChanged ( "Contact" );
        }
    }


    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    void OnPropertyChanged ( string propName )
    {
        if ( this . PropertyChanged != null )
            this . PropertyChanged (
                this , new PropertyChangedEventArgs ( propName ) );
    }

    #endregion


    public Conversation ( Friend _Friend )
    {
        InitializeComponent ( );

        Contact = _Friend;
    }

    .
    .
    .

}

C# Friend Class

public class Friend : Person
{

    .
    .
    .

}

C# Person Class

public class Person : INotifyPropertyChanged 
{       

    private string _Name;

    public string Name
    {
        get
        {
            return _Name;
        }
        set
        {
            _Name = value;
            OnPropertyChanged ( "Name" );
        }


    #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged ( string propName )
        {
                if ( this . PropertyChanged != null )
                this . PropertyChanged ( this , new PropertyChangedEventArgs ( propName ) );
        }

    #endregion


    .
    .
    .


}

My Question : Why Binding Doesn't Work ?

Upvotes: 0

Views: 101

Answers (2)

Danny Varod
Danny Varod

Reputation: 18068

As wangberger stated, contact must be a property.

As wangberger implied, you did not set the DataContext of the binding target (TextBlock control) or any of its ancestors (e.g. the window) to the binding source (in your case the window itself).

Also, please read Microsoft's .NET Guidelines regarding naming conventions.

P.S. Setter should only raise PropertyChanged if value != _name;

Upvotes: 1

wangburger
wangburger

Reputation: 1083

Contact needs to be a property rather than a field.

Also, you need to change the binding so that the source is the window class.

Upvotes: 4

Related Questions