I’m creating a simple code generator with delegates.
Why am I getting this error at runtime:
Error while binding the target method.
on the following code?
XAML:
<Window x:Class='Parser.Window1' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Loaded='Window_Loaded' Title='Parser' Height='600' Width='800'> <TextBox x:Name='Output' VerticalScrollBarVisibility='Visible' Margin='10'/> </Window>
Code-Behind:
using System; using System.Collections.Generic; using System.Text; using System.Windows; namespace Parser { public partial class Window1 : Window { private List<string> _fields; public Window1() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { _fields = new List<string> { 'CustomerID', 'CompanyName', 'ContactName', 'ContactTitle', 'Address', 'City', 'Region', 'PostalCode', 'Country', 'Phone', 'Fax' }; Output.Text += ParseFieldsWithMethod('BuildAssignmentLines'); Output.Text += ParseFieldsWithMethod('BuildEnabledLines'); } private string ParseFieldsWithMethod(string theParseMethod) { Predicate<string> predicate = (Predicate<string>)Delegate.CreateDelegate(typeof(Predicate<string>), typeof(Window1).GetMethod(theParseMethod)); StringBuilder sb = new StringBuilder(); foreach (var field in _fields) { sb.Append(predicate.Invoke(field)); } return sb.ToString(); } public string BuildAssignmentLines(string field) { return String.Format('customer.{0} = Field_{0}.Text;\n', field); } public string BuildEnabledLines(string field) { return String.Format('Field_{0}.IsEnabled = false;\n', field); } } }
Predicate is a function that takes a string as a parameter and returns a boolean. Yours return strings.
You should use Function instead of Predicate.
Also, you should really send the function as a parameter and not by name.