System.Reflection.TargetParameterCountException was unhandled Dispatch. Invoke error

Oct 3, 2012 at 1:37 PM

The bigger idea is to be able to pass arrays of data from logic classes to presentation layer. This is an example below from Stackflow which works fine with Windows forms but I am trying to implement it in WPF.The Invoke is having parameter mismatch - can anyone have a try please. Create a WPF project and add MyClass.cs file with the first code snippet (1. MyClass.cs), then drag button and  richTextbox to WPF MainWindow. see below: please. I will be very grateful for any help that will resolve the error on this line of code target.Dispatcher.Invoke( DispatcherPriority.Normal, Message ).

 

1. MyClass.cs

public delegate void MyDelegate(object sender, string message);

    public class MyClass
    {
       
      
        public event MyDelegate Message;

        public void MyFunction()
        {
            // TODO: Do something.
            OnMessage("MY DATA");
        }

        protected void OnMessage(string message)
    {
        // If event is wired, fire it!
        if( Message != null )
        {
            // Get the target and safe cast it.
            Control target = Message.Target as Control;
          
            // If the target is an control and invoke is required,
            // invoke it; otherwise just fire it normally.
            if( target != null && target.Dispatcher.CheckAccess())
            {
                object[] args = new object[] { this, message };
                target.Dispatcher.Invoke( DispatcherPriority.Normal, Message );
            }
            else
            {
                Message( this, message );
            }
        }
    }
    }


2. MainWindow.cs
public partial class MainWindow : Window
    {
        private MyClass _myClass;


        public MainWindow()
        {
            InitializeComponent();
        }

        private void Grid_Loaded_1(object sender, RoutedEventArgs e)
        {
         
        }

        private void _myClass_Message(object sender, string message)
        {
            // Append the message.
            rtbox.AppendText(message);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            // Initialize member and wire event.
            _myClass = new MyClass();
            _myClass.Message += new MyDelegate(_myClass_Message);
            _myClass.MyFunction();
        }

    }