0

Possible Duplicate:
Bind to a method in WPF?

Is there a simple way to access a method form my code behind in XAML?

I've seen solutions that use ObjectDataProvider, but from my understanding they create a new instace of the given type and call the method of this object. This would be of no use for me, as I need to call the actual code of my class (datacontext is important for methods!)…

Route.xaml.cs: public string GetDifficultyName(int id);

Route.xaml: Displays a list of routes

Every route has a property "DiffId", that has to be passed to the method above and the result has to be set as value to a textbox -> resolves the id to a human readable description.

Community
  • 1
  • 1
MFH
  • 1,664
  • 3
  • 18
  • 38
  • Check [my answer here](http://stackoverflow.com/questions/502250/bind-to-a-method-in-wpf/844946#844946) that shows how to bind to a method within WPF XAML. – Drew Noakes Dec 23 '10 at 19:38

1 Answers1

1

A simple way of doing this is exposing a ValueConverter instance as a resource in your Window (or Control or whatever) which has been initialized in your code-behind appropriately to call into the method(s) you require.

For example:

[ValueConversion(typeof(object), typeof(string))]
public class RouteDifficultyNameConverter : IValueConverter
{
    private readonly IMyMethodProvider provider;

    public RouteDifficultyNameConverter(IMyMethodProvider provider)
    {
        this.provider = provider;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return provider.GetDifficultyName((int)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

This is not a properly complete converter of course, but you get the idea.

And in your code-behind's constructor:

    this.Resources.Add("routeDifficultyConverter",
                       new RouteDifficultyNameConverter(this));
    this.InitializeComponent();
Jon
  • 428,835
  • 81
  • 738
  • 806