WPF Binding INotifyPropertyChangedマルチスレッドの理解
7577 ワード
Person.cs
public class Person : ObservableObject,INotifyPropertyChanged
{
private string _testName;
private ObservableCollection<string> _names=new ObservableCollection<string>();
public string TestName
{
get
{
return _testName;
}
set
{
_testName = value;
OnPropertyChanged();
}
}
public ObservableCollection<string> Names
{
get { return _names; }
set
{
_names = value;
RaisePropertyChanged(()=>Names);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
MainWindow.xaml.cs
public partial class MainWindow : Window, INotifyPropertyChanged
{
private int _currentId;
private Person _person;
public Person Person
{
get
{
return _person;
}
set
{
_person = value;
OnPropertyChanged();
}
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
Person = new Person();
Person.TestName = "TestName";
Person.Names.Add("string");
_currentId = Thread.CurrentThread.ManagedThreadId;
DispatcherHelper.Initialize();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(() =>
{
if (_currentId == Thread.CurrentThread.ManagedThreadId)
{
Person = new Person();
}
else
{
// ?
Person.TestName = "NotSame";
// ?
Person.Names.Add("Hello");
}
});
}
}
注釈の注意点
その結果、TestName属性はUIに正しく更新されますが、集合属性Namesはできません(ここでは確かに理解していません.教えてください).
残りの理解はよく書けている.
http://www.cnblogs.com/wpcockroach/p/3909081.html