在我的MainViewModel
我订阅Event
:
var uc = new MyUserControl();
uc.ViewModel.ValueTypeChangedEvent += OnValueTypeChanged;
Control05 = uc;
StartMeasuring2();
我BackgroundWorker
的是:
private myUserControl Control05 { get; set; }
private void StartMeasuring2()
{
_backgroundWorkerP2.RunWorkerCompleted += backgroundWorkerCompleted;
_backgroundWorkerP2.DoWork += BackgroundWorkerDoWork;
if (_backgroundWorkerP2.IsBusy)
_backgroundWorkerP2.CancelAsync();
else
{
_backgroundWorkerP2.RunWorkerAsync();
}
}
private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs eventArgs)
{
Thread.Sleep(3000);
while (!StopMeasuringP2)
{
const int measurementStatus = 0;
var random = new Random();
double measurementValue = random.Next(1, 9);
var dateTime = DateTime.Now;
Control05.ViewModel.UserControl1.ViewModel.LastDayMesswerte(dateTime,measurementValue, measurementStatus);
Thread.Sleep(7000);
}
}
编辑:
这是我在用户控件中的 LastDayMesswerte 方法ViewModel
:
public virtual void LastDayMesswerte(DateTime time, double measurementValue, int measurementStatus)
{
if(measurementValue>=0 && measurementValue<3)
ValueType = "Alarm";
if(measurementValue>=3 && measurementValue<6)
ValueType = "Warning";
else
{
ValueType = "Normal";
}
}
我ValueType
的财产:
public virtual string ValueType
{
get { return _valueType; }
set
{
if (_valueType == value) return;
_valueType = value;
OnValueTypeChangedEvent(ControlId, MasterId);
}
}
OnValueTypeChangedEvent
:
protected virtual void OnValueTypeChangedEvent(int controlId, int masterId)
{
ValueTypeChangedEventHandler handler;
lock (_valueTypeChangedEventLock)
{
handler = _valueTypeChangedEvent;
}
if (handler != null) handler(controlId, masterId);
}
LastDayMesswerte
所以在我调用之前BackgroundWorker
, _valueTypeChangedEvent
不是 NULL。我在方法中的第一个 if 语句上设置了一个断点,LastDayMesswerte
并且_valueTypeChangedEvent
已经是 NULL。为什么会这样?