约束问题

时间:2011-05-22 20:21:31

标签: wpf data-binding

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# 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#朋友类

public class Friend : Person
{

    .
    .
    .

}

C#人员类

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


    .
    .
    .


}

我的问题:为什么绑定不起作用?

2 个答案:

答案 0 :(得分:4)

联系人需要是财产而不是领域。

此外,您需要更改绑定,以便源是窗口类。

答案 1 :(得分:1)

正如wangberger所说,联系必须是财产。

正如wangberger暗示的那样,你没有将绑定目标(TextBlock控件)或其任何祖先(例如窗口)的DataContext设置为绑定源(在你的情况下是窗口本身)。

另外,请阅读Microsoft关于命名约定的.NET指南。

P.S。如果值为!= _name;

,Setter应该只提升PropertyChanged