2013-03-05 147 views
6

我长时间没有成功地寻找解决这个问题的方法。F#dispatcher.invoke和委托方法

我正在将一些C#代码移植到F#,并且我正在为WPF元素使用Dispatcher.Invoke。由于我是F#中的总noob,我唯一能确定的是问题出现在椅子和键盘之间。

这里是我的C#代码:

foreach (var k in ChartList.Keys)    
     { 
      ChartList[k].Dispatcher.Invoke(
       System.Windows.Threading.DispatcherPriority.Normal, 
       new Action(
       delegate() 
       { 
        ChartList[k].Width = area.Width/totalColsForm; 
        ChartList[k].Height = area.Height/totalRowsForm; 
        ChartList[k].Left = area.X + ChartList[k].Width * currentCol; 
        ChartList[k].Top = area.Y + ChartList[k].Height * currentRow; 
        ChartList[k].doShow(); 
       } 
      )); 
     } 

我挣扎的部分是新的行动(委托()...)。编译器不喜欢我翻译它的任何尝试。

这段代码在F#中的翻译是什么?

+0

你试图做什么?我期望'fun() - > ...'或者'Action(fun() - > ...)'工作。 – Daniel 2013-03-05 15:51:31

+0

@丹尼尔,正是我尝试都没有成功。我得到了错误“没有重载匹配的方法”Invoke'“=>它是委托方法的翻译是问题 – Anass 2013-03-05 16:18:19

回答

6

Invoke方法有几个重载,所以如果你在动作中有不完全正确的东西,你可能会有一些奇怪的错误,因为类型检查器不知道要调用哪个超载。我只是试过这个,它工作得很好:

open System 
open System.Windows.Controls 
open System.Windows.Threading 

let b = Button() 
b.Dispatcher.Invoke(
    DispatcherPriority.Normal, 
    Action(fun() -> 
     b.Content <- "foo" 
    )) |> ignore 
+0

Thx Gustavo,我试过你的代码,但我仍然有同样的错误,我得到的是”无效使用接口类型“,而术语”行动“则加下划线。 我想出了一个我自己的解决方案。我宣布明确 型my_delegate =单位的代表 - >单元 和我的代码变得 对于k在ChartList.Keys做 ChartList [K] .Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,新。 my_delegate(fun() - > ChartList。[k] .doShow()))|>忽略 代码编译但我仍然不明白为什么使用Action会引发错误 – Anass 2013-03-05 17:00:44

+0

您是否碰巧有任何接口行动?尝试拼出System.Action – 2013-03-05 17:06:52

+0

它的工作!感谢古斯塔沃,但我不明白我拥有所需的所有参考,以及所需的开放语句。奇! – Anass 2013-03-05 17:13:33