WPF Binding to method of a collection element
-
19-09-2019 - |
Question
Im searching for the best practice (or any working solution) for the following scenario:
I have an Employee
class:
public class Employee
{
public string DisplayName
{ get; set; }
// It is important that this method has a parameter
public string GetSomething(string param)
{ return param + DisplayName; }
}
I have a List<Employee>
type object which is bound to a ComboBox in XAML.
The DisplayName for each employee is correctly showing in the ComboBox, but how can I show the return value of the GetSomething method with an exact parameter for all employees for each employee instead of the DisplayName?
Binding to a method is OK, but how can I bind to multiple instances (for each employee object in the list)? With the ObjectDataProvider
I can only bind to one exact instance (or a class), not each employee object of the employee list.
Solution
Save yourself some trouble: use a view model and create a separate property that returns the value you want for each employee. To give a more detailed answer, I need to know where the parameter comes from.
OTHER TIPS
I agree with @Kent Boogaart that using a view model is definitely the desired way to go (as well as a best practice).
Another possibility that I have used before (before I knew more about Model-View-ViewModel) is to use a BindingConverter. Bind either to your Employee class or to the DisplayName property and pass in the parameter as the parameter to the binding converter.