gpt4 book ai didi

wpf - Winforms 到 WPF 转换 : BeginInvoke to what?

转载 作者:行者123 更新时间:2023-12-04 03:14:12 24 4
gpt4 key购买 nike

这是我来自 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");
});
}
}

但是第二个“委托(delegate)”电话失败了。我怎样才能调用这个委托(delegate)?我想我可以完成整个制作委托(delegate)方法,制作委托(delegate)方法的实例,调用该特定实例等,但我认为这些匿名委托(delegate)的全部意义在于避免这种麻烦。另外,我的旧 winforms 代码到处都有第一个实现,所以我真的很想避免对我的所有委托(delegate)进行去匿名化。

编辑:我可以尝试像以前一样使用 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 的使用是不洁的。是否有单独的实现,或其他方式来使用相同的行为?

最佳答案

System.Windows.Forms.MethodInvoker 只是一个不带参数并返回 void 的委托(delegate)。在 WPF 中,您可以将其替换为 System.Action .还有其他内置的委托(delegate) accept parameters , return values , 或 both .

在你的情况下,

ValueLabel.Dispatcher.BeginInvoke(new System.Windows.Forms.MethodInvoker(delegate {
ValueLabel.Content = (inValue1* inValue2/ 1000).ToString("f1");
}));

变成
ValueLabel.Dispatcher.BeginInvoke(new Action(delegate() {
ValueLabel.Content = (inValue1* inValue2/ 1000).ToString("f1");
}));

关于wpf - Winforms 到 WPF 转换 : BeginInvoke to what?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/758233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com