2013-11-22 65 views
0

我所面臨的問題的對象,我有對象的名單,讓說的人:的數據綁定到列表

class Person : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 
    private string _name; 
    private string _surname; 
    public string name 
    { 
     get { return _name; } 
     set { SetField(ref _name, value, "name"); } 

    } 
    public string surname 
    { 
     get { return _surname; } 
     set { SetField(ref _surname, value, "surname"); } 

    } 
    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(propertyName)); 

     } 
    } 
    protected bool SetField<T>(ref T field, T value, string propertyName) 
    { 
     if (EqualityComparer<T>.Default.Equals(field, value)) return false; 
     field = value; 
     OnPropertyChanged(propertyName); 
     return true; 
    } 
} 

和XAML:

<TextBlock HorizontalAlignment="Left" Margin="310,167,0,0" TextWrapping="Wrap" Text="{Binding Path=name}" VerticalAlignment="Top" FontSize="36"/> 
    <TextBlock HorizontalAlignment="Left" Margin="585,167,0,0" TextWrapping="Wrap" Text="{Binding Path=surname}" VerticalAlignment="Top" FontSize="36"/> 
    <Button Content="Button" HorizontalAlignment="Left" Margin="721,355,0,0" VerticalAlignment="Top" Click="Button_Click"/> 

在頁面初始化我這樣做:

List<Person> Persons = new List<Person>(); 
    public MainPage() 
    { 
     this.InitializeComponent(); 

     Person a = new Person(); 
     a.name = "First"; 
     a.surname = "FirstSurname"; 
     Persons.Add(a); 
     Person b = new Person(); 
     b.name = "Second"; 
     b.surname = "SecondSurname"; 
     Persons.Add(b); 
     this.DataContext = Persons[0]; 
    } 

的,我不想改變的財產,但改變整個對象:

private void Button_Click(object sender, RoutedEventArgs e) 
    { 

     Person a = new Person(); 
     a.name = "Test"; 
     a.surname = "Test"; 
     Persons[0] = a; 
    } 

我怎樣才能讓我的TextBlocks自動reget數據?不要做this.DataContext =人[0];再次

+0

爲什麼你有一個'名單',當你只想綁定到第一個元素?爲什麼'MainPage'中沒有'CurrentPerson'屬性(包含更改通知)? – Clemens

回答

0

文本財產在你的TextBlock,嘗試設置UpdateSourceTrigger的PropertyChanged

Text="{Binding Path=name, UpdateSourceTrigger=PropertyChanged}" 
+0

\t錯誤C對元素 '綁定' \t \t 1未知成員 'UpdateSourceTrigger':\用戶\ afomenko \文件\視覺工作室2012 \項目\ APP5 \ APP5 \ MainPage.xaml中\t APP5 – Cheese

+0

但是它不會無論如何幫助,因爲我沒有改變屬性,我正在改變整個對象 – Cheese

+0

你是圍繞DataTemplate或其他東西包裝兩個TextBlocks和Button嗎?我假設列表中的「人員」數量會動態變化。如果你有一個帶有TextBlocks和Button的DataTemplate,你可以將它的** ItemsSource **設置到列表中,並將它的** UpdateSourceTrigger **設置爲** PropertyChanged **。 – Zinthos