开发者

Binding Problem

开发者 https://www.devze.com 2023-03-08 02:27 出处:网络
XAML <TextBlock Grid.Column=\"1\" Height=\"37\" Margin=\"8,17,0,0\" HorizontalAlignment=\"Left\" VerticalAlignment=\"Top\"

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
        开发者_C百科{
            _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 ?


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.


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;

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号