사업 개요데이터 IPropertyChangedNotify 호출에서 새 데이터를 선택하지 않습니다
기본적으로 내가 MVVM 패턴을 사용하여 WPF 응용 프로그램을 작성했다. 그러나 내 데이터 모델을 업데이트하는 스레드가있어서 ViewModel에 이러한 알림이 전송되어야하고 모델에 알림 메커니즘이 필요했습니다. 그렇게하면 내 앱이 한 클래스에서 다른 클래스로 알림을 전파하도록 만들 것이므로 View에 직접 이야기하는 모델을 갖기로 결정했습니다. 내 모델을 코드의 나머지 부분과 분리하기 위해 다른 기술을 사용 했으므로 여전히 내 로직을 분리했습니다. 내 UI에서.
문제 내 스레드 모델의 값을 변경
, 그것은 그러나 내보기 변경을하지 않고는 OnPropertyChanged()
호출합니다.
코드
스레드 (이 내 프로젝트의 단순화 된 버전입니다) 어떤 업데이 트 모델
class MyThread
{
Model mdl;
public MyThread()
{
mdl = new Model();
}
public Model getModel()
{
return mdl;
}
public void run()
{
while (true)
{
mdl.Age++;
Thread.Sleep(1000);
}
}
}
내 모델
class Model : INotifyPropertyChangedBase
{
private int _age = 0;
public int Age
{
get { return _age; }
set
{
var init = _age;
this.CheckPropertyChanged<int>("Age", ref init, ref value);
}
}
}
내보기는 다음 바인딩
<TextBlock Text="{Binding Age}" />
코드에 대한 INotifyPropertyChangedBase 내 컨트롤의 DataContext에 나의 모델에 할당
namespace BindingTesting
{
public abstract class INotifyPropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
#region Methods
[Conditional("DEBUG")]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
// verify that the property name matches a real,
// public, instance property on this object.
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
Debug.Fail("Invalid property name: " + propertyName);
}
}
protected bool CheckPropertyChanged<T>(string propertyName, ref T oldValue, ref T newValue)
{
if (oldValue == null && newValue == null)
{
return false;
}
if ((oldValue == null && newValue != null) || !oldValue.Equals((T)newValue))
{
oldValue = newValue;
OnPropertyChanged(propertyName);
return true;
}
return false;
}
protected void OnPropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName);
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
기타 정보 있습니다. 그것은 DependecyProperty를 대신 사용하면 절대적으로 올바르게 작동합니다. get 메서드는 호출되지만 데이터는 업데이트되지 않습니다.
당신은 단지 확인 Object.Equals (oldValue입니다, NEWVALUE)에 의해 CheckPropertyChanged 단순화 할 수 있습니다, 이것은 실제로 당신의 코드가 수행 정확히 무엇을 할 것입니다. –