silverlight依赖属性

1.一个实体类,需要实现“INotifyPropertyChanged”接口

 

代码
     public   class  student : INotifyPropertyChanged
    {
        
string  name;

        
public   string  Name
        {
            
get  {  return  name; }
            
set
            {
                name 
=  value;

                
// 这里需要传递“Name”,而不是私有变量“name”
                NotifyPropertyChange( " Name " );       
            }
        }

        
public   int  age {  get set ; }

        
#region  INotifyPropertyChanged 成员

        
public   event  PropertyChangedEventHandler PropertyChanged;        // INotifyPropertyChanged接口委托
         private   void  NotifyPropertyChange( string  propertyName)
        {
            
if  (PropertyChanged  !=   null )
            {
                
// 通知更新所有绑定了propertyName,属性的控件更新界面值
                PropertyChanged( this new  PropertyChangedEventArgs(propertyName));
            }
        }

        
#endregion
    }

 

 

2.在xaml中,设置控件的绑定更新方向: <sdk:Label Height="28" Content="{Binding Name,Mode=TwoWay}"

 

代码
     < Grid x:Name = " LayoutRoot " >
        
< TextBox Height = " 23 "  HorizontalAlignment = " Left "  Margin = " 250,144,0,0 "  Name = " txtName "  VerticalAlignment = " Top "  Width = " 120 "   />
        
< sdk:Label Height = " 23 "  Content = " 名称: "  HorizontalAlignment = " Left "  Margin = " 175,144,0,0 "  Name = " label1 "  VerticalAlignment = " Top "  Width = " 69 "   />
        
< Button Content = " 确定 "  Height = " 23 "  HorizontalAlignment = " Left "  Margin = " 250,215,0,0 "  Name = " btnOK "  VerticalAlignment = " Top "  Width = " 75 "  Click = " btnOK_Click "   />
        
< sdk:Label Height = " 28 "  Content = " {Binding Name,Mode=TwoWay} "  HorizontalAlignment = " Left "  Margin = " 175,103,0,0 "  Name = " labMessage "  VerticalAlignment = " Top "  Width = " 120 "   />
        
< TextBox Height = " 23 "  HorizontalAlignment = " Left "  Margin = " 250,173,0,0 "  Name = " txtAge "  VerticalAlignment = " Top "  Width = " 120 "   />
        
< sdk:Label Content = " 年龄: "  Height = " 23 "  HorizontalAlignment = " Left "  Margin = " 175,173,0,0 "  Name = " label3 "  VerticalAlignment = " Top "  Width = " 69 "   />
    
</ Grid >

 

 

3.在cs代码中更新实体类的依赖属性

 

代码
     public   partial   class  Page1 : Page
    {
        student myStudent 
=   new  student();

        
public  Page1()
        {
            InitializeComponent();

            myStudent.Name 
=   " 张三 " ;
            myStudent.age 
=   20 ;

            
this .DataContext  =  myStudent;
        }

        
private   void  btnOK_Click( object  sender, RoutedEventArgs e)
        {
            
// myStudent.Name更新的同时,也会自动更新labMessage.Content的值
            myStudent.Name  =  txtName.Text;
        }
    }

 

 

 

你可能感兴趣的:(silverlight)