Im trying to apply a filter to a DataGrid in WPF and the filter property needs a Predicate
ex:
dataGrid1.Filter = p => p.A_Field_Table1.Contains(textBox.Text);
But my datagrid is being filled with reflection, so I only know the type of objects inside the datagrid at runtime.
Then I created a method that dynamically generates the Predicate< T > :
public static Predicate< T > GetPredicate< T >(string column, string valueP, T objSource, string table)
{
Type itemType = typeof(T);
ParameterExpression predParam = Expression.Parameter(itemType, "p");
Expression left = Expression.Property(predParam, itemType.GetProperty("A_" + column+ "_" + table));
var valueStr= Expression.Constant(valueP);
var typeOfStr = valueStr.Type;
var containsMethod = typeOfStr.GetMethod("Contains", new [] { typeof(string) });
var call = Expression.Call(left, containsMethod, valueStr);
Func< T, bool > function = (Func< T, bool >)Expression.Lambda(call, new[] { predParam }).Compile();
return new Predicate< T >(function);
}
Then call this function on the interface:
var dataGridItem = dataGrid.Items[0];
dataGrid1.Filter = Class_X.GetPredicate(columnRefName,textBox.Text,dataGridItem,tableRefName);
But the generic method is throwing an exception saying that the type T is type of "object", even if objSource is type of Model.TableName.
I read some tutorials saying that T could not be resolved at runtime, then I should use "dynamic" instead of generic types.
I already tried using the "dynamic" type but I get a exception while casting the Lambda expression to Func< dynamic, bool>. Saying that I can't convert from < Model.TableName , bool > to < System.Object , bool >.
Is there an easier way to filter a datagrid that was filled by reflection?