C# Delegate Action 是如何用 F# 编写的?

How is the C# Delegate Action written in F#?

如何在 F# 中实现 C# 动作?

我在 C# 代码隐藏中有以下代码:

public MainWindow()
        {
            InitializeComponent();
            ViewModel = new ViewModel();
            DataContext = ViewModel;
        }

        private void ListView_PreviewMouseLeftButtonUp(object _, MouseButtonEventArgs e)
        {
            _closeAdorner();
        
            // listView here equals object _  
            var listView = (ListView)e.Source;
            var grid = (Grid)listView.Parent;
            var selecteditem = (InnerRow)listView.SelectedItem;
            ViewModel.Visit = selecteditem;
            ViewModel.LastName = selecteditem.LastName;
        
            var adornerLayer = AdornerLayer.GetAdornerLayer(grid);
            if (adornerLayer == null)
                throw new ArgumentException("datagrid does not have have an adorner layer");

            var adorner = new DataGridAnnotationAdorner(grid);
            adornerLayer.Add(adorner);
        
           _closeAdorner = () => adornerLayer.Remove(adorner);
        }

我正在尝试将其翻译成 F#:

let handlePreviewMouseLeftButtonUp (obj: obj) (a, c) =
      let e = (obj :?> MouseButtonEventArgs)
      let listView = e.Source :?> ListView   // This is the ListView control that was clicked.
      let grid = listView.Parent :?> Grid
          
      let selectedItem = c.InnerRows |> List.filter (fun r -> Some r.Id = c.SelectedInnerRow) |> List.head
    
      let adorner = DataGridAdorner(grid)

      let installAdorner =
        let adornerLayer = AdornerLayer.GetAdornerLayer(grid)
        if (adornerLayer.GetAdorners = []) then adornerLayer.Add(adorner) else adornerLayer.Remove(adorner)
 

最后一行: if (adornerLayer.GetAdorners = []) then adornerLayer.Add(adorner) else adornerLayer.Remove(adorner)

显然不编译也不正确。 C#的_closeAdorner是如何写成在F#中具有相同功能的?

谢谢。

TIA

我不确定 _closeAdornerInnerRowDataGridAdorner 和其他元素是什么。不管怎样,我在这里修复了你代码中的一些(不是全部)语法问题:

let handlePreviewMouseLeftButtonUp(obj : obj) (e:MouseButtonEventArgs)  =
    let listView = e.Source        :?> ListView   // This is the ListView control that was clicked.
    let grid     = listView.Parent :?> Grid
        
    let selectedItem = listView.SelectedItem :?> InnerRow//  |> List.filter (fun r -> Some r.Id = c.SelectedInnerRow) |> List.head
    
    let adorner = DataGridAdorner(grid)

    let installAdorner =
        let adornerLayer = AdornerLayer.GetAdornerLayer(grid)
        if adornerLayer.GetAdorners(grid) = [||] then adornerLayer.Add(adorner) else adornerLayer.Remove(adorner)
    ()

在您的构造函数中,您可以像这样添加事件处理程序:

listView.MouseUp.AddHandler(MouseButtonEventHandler(handlePreviewMouseLeftButtonUp))

您也可以删除它:

listView.MouseUp.RemoveHandler(MouseButtonEventHandler(handlePreviewMouseLeftButtonUp))

要创建通用 Actions,您可以这样做:

let action = Action<_,_>(handlePreviewMouseLeftButtonUp)

其中<_,_>对应动作接收的参数个数。