我遇到了一个问题,我有一个对象列表,让我们说人:
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自动重新获取数据?不做这个.DataContext = Persons [0];再次
答案 0 :(得分:0)
在 TextBlock 的文字属性中,尝试将 UpdateSourceTrigger 设置为 PropertyChanged :
Text="{Binding Path=name, UpdateSourceTrigger=PropertyChanged}"