开发者

XAML access method in code behind [duplicate]

This question already has answers here: Closed 10 years ago.

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 m开发者_JAVA百科ethod 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.


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜