我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);
}
}
是:
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";
}
}
中的LastDayMesswerte方法:
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
之前,LastDayMesswerte
不是NULL。我在方法_valueTypeChangedEvent
中的第一个if语句上设置了断点,{{1}}已经为NULL。为什么会这样?
答案 0 :(得分:1)
执行后尝试启动后台工作程序:
var uc = new MyUserControl();
uc.ViewModel.ValueTypeChangedEvent += OnValueTypeChanged;
并且还要确保您提升事件的视图模型的实例是您的用户控件视图模型。希望这个提示有帮助...
修改强>
您是否尝试使用SynchronizationContext
执行在另一个线程中引发事件的操作?像这样:
//Register the events
var currentSyncContext = SynchronizationContext.Current;
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (_,__) =>
{
//some action in background
currentSyncContext.Send((t) =>
{
//Action that raise the event
}, null);
};
backgroundWorker.RunWorkerAsync();
也许这有效,试试吧......
答案 1 :(得分:1)
如果我没有弄错(你的代码很不寻常 - 我不会从ViewModel创建一个UserControl,它在ViewModel中包含另一个UserControl,它本身也有一个ViewModel),问题在于
Control05.ViewModel.UserControl1.ViewModel.LastDayMesswerte(...)
您在LastDayMesswerte
中致电Control05.ViewModel.UserControl1.ViewModel
,但您从未在那里设置ValueTypeChangedEvent
。而是将其设置为Control05.ViewModel
。