2012-04-25 110 views
2

我在Page類有一個屬性(MainStudent):綁定到財產

public partial class AddStudent : Page 
{ 
    public AddStudent() 
    { 
     InitializeComponent(); 
     MainStudent = new Student(); 
    } 

    public Student MainStudent 
    { 
     get; 
     set; 
    } 
} 

什麼是MainStudent物業的名字屬性綁定(學生類有一些方法的最佳方式。例如:名字, )到XAML中TextBox的Text屬性?

回答

2

如果您Page具有性質請參閱Student您可以直接在此處設置其DataContext,作爲您當前構造函數中的最後一行:

this.DataContext = this.MainStudent; 

,然後在XAML做綁定直接到學生的屬性:

<TextBox Text="{Binding FistName}"></TextBox> 

,否則你可以設置的DataContext你Page的本身:

this.DataContext = this; 

,做綁定,如:

<TextBox Text="{Binding MainStudent.FirstName}"></TextBox> 
0

使用下,如果包含 「MainStudent」 之類的是你的DataContext 對於實例

<Grid DataContext="{StaticRessource YourViewModelDefinedInRessources}"> 
    <TextBox Text="{Binding MainStudent.FirstName}" /> 
    <TextBox Text="{Binding MainStudent.LastName}" /> 
</Grid> 

如果您需要進一步的幫助,就問;)

1
<TextBox Text="{Binding MainStudent.Firstname, UpdateSourceTrigger=PropertyChanged}"/> 
+0

請注意,使用UpdateSourceTrigger = PropertyChanged鍵入的每個字符都會調用setter。否則Setter被調用失去焦點 – sebastianmehler 2012-04-25 08:51:39

+1

它通知視圖模型已更改,因此可以更新視圖。 http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx – 2012-04-25 09:02:27