这是我在 WinForms 中的旧代码:
private void ValueChanged(double inValue1, double inValue2) {
//only manual mode for this driver, so that's easy.
if (ValueLabel.InvokeRequired) {
ValueLabel.Invoke(new MethodInvoker(delegate {
ValueLabel.Text = (inValue1* inValue2/ 1000).ToString("f1");
}
));
}
else {
ValueLabel.Text = (inValue1* inValue2/ 1000).ToString("f1");
}
}
有没有一种简单的方法可以将其转换为 WPF 友好的?到目前为止,我有:
private void KVPValueChanged(double inValue1, double inValue2) {
if (ValueLabel.Dispatcher.Thread == Thread.CurrentThread){
ValueLabel.Content = (inValue1* inValue2/ 1000).ToString("f1");
} else {
ValueLabel.Dispatcher.BeginInvoke(delegate {
ValueLabel.Content = (inValue1* inValue2/ 1000).ToString("f1");
});
}
}
但第二个“委托”调用失败了。我怎样才能调用这个委托?我想我可以完成创建委托方法、创建委托方法的实例、调用该特定实例等的整个过程,但我认为这些匿名委托的全部目的是避免这种麻烦。另外,我的旧 winforms 代码到处都有第一个实现,所以我真的很想避免必须对所有代表进行去匿名化。
Edit:我可以尝试像以前一样使用 MethodInvoker,但编译器会感到困惑。 MethodInvoker 是 System.Windows.Forms 的一部分,因此使用该方法不起作用。如:
private void ValueChanged(double inValue1, double inValue2) {
if (ValueLabel.Dispatcher.Thread == Thread.CurrentThread) {
ValueLabel.Content = (inValue1* inValue2/ 1000).ToString("f1");
}
else {
ValueLabel.Dispatcher.BeginInvoke(new System.Windows.Forms.MethodInvoker(delegate {
ValueLabel.Content = (inValue1* inValue2/ 1000).ToString("f1");
}));
}
}
MethodInvoker 的使用是不合规矩的。是否有单独的实现,或者使用相同行为的其他方式?