我所面臨的問題的對象,我有對象的名單,讓說的人:的數據綁定到列表
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];再次
爲什麼你有一個'名單',當你只想綁定到第一個元素?爲什麼'MainPage'中沒有'CurrentPerson'屬性(包含更改通知)? –
Clemens