XAML access method in code behind [duplicate]
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();
精彩评论