如何分派相同的方法多次调用并在 WPF 应用程序中将调用顺序编号作为参数?

How can I dispatch same method to be called multiple times and give call order number as parameter in WPF app?

我只需要为每个视图模型分派一个方法一次并且一切正常。现在我需要为其中一个视图模型(下面的 ObjectViewModel)分派 SelectedObjectsChanged 调用 2 次,所以我为这两种方法引入了 属性 NumberOfCalls 和参数。但是 SelectedObjectsChanged 只被调用一次,参数 callNumber 的值是错误的 (2),而我认为第一次是 0,第二次是 1。这应该如何正确完成?

interface ISelectedObjectDependent
{
    void SelectedObjectsChanged(int callNumber);
    int NumberOfCalls { get; }
    int ExecutionOrder { get; }
    bool NeedsRefresh(int callNumber);
}

public class SelectedObjects
{
    private List<ISelectedObjectDependent> _viewModels; 
    public void ObjectSelectionChanged(object sender, EventArgs e)
    {
        foreach (var vm in _viewModels)
        {
            for (int i = 0; i < vm.NumberOfCalls; i++)
            {
                if (vm.NeedsRefresh(i))
                {
                    App.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, 
                        (Action)(() => 
                   {
                       vm.SelectedObjectsChanged(i);
                   }));
                }
            }
        }
    }
}

public class ObjectViewModel : ViewModel, ISelectedObjectDependent
{
    public int NumberOfCalls { get { return 2; } }

    public int ExecutionOrder { get { return 1;} }

    public bool NeedsRefresh(int callNumber)
    {
        return true;
    }

    public void SelectedObjectsChanged(int callNumber)
    {
         if (callNumber == 0)
         {
            if (IsObjectInfoVisible && IsObjectInformationExpanded)
                RefreshObjectInfo(false);
         }
         else
         {
             if (IsObjectInfoVisible && IsObjectInformationExpanded)
                 ObjectProperties.Instance.UpdateRemainingAttributes();
         }
    }
}

在 SelectedObjectsChanged 执行时值已经改变

var index = i;                    
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)(() => 
               {
                   vm.SelectedObjectsChanged(index);
               }));

PhillipH 的有用评论

All delegate style code blocks in .net have the same scenario. If you are passing an iterated variable, it does not get evaluated until the code block is executed. You think it gets evaluated when you create the code block, but its a misreading of the code