Bind to extension method in WPF
binding, c#, extension-methods, wpf
Solution
No, you cannot bind to an extension method. You can bind to the `Name`-property of the `Dog`-object and use a converter though.
To create a converter create a class implementing the `IValueConverter` interface. You will need a one-way conversion only (from the model to the view) so will need to implement the `Convert` method only. The `ConvertBack` method is not supported by your converter and thus throws a `NotSupportedException`.
public class NameToBarkConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var dog = value as Dog;
if (dog != null)
{
return dog.BarkYourName();
}
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
Then you can use your converter as follows:
<Grid>
<Grid.Resources>
<NameToBarkConverter x:Key="NameToBarkConverter" />
</Grid.Resources>
<TextBlock Text="{Binding Name, Converter={StaticResource NameToBarkConverter}}" />
</Grid>
For more information on converters see MSDN: IValueConverter.
Problem
I have a simple class in C#: ``` public class Dog { public int Age {get; set;} public string Name {get; set;} } ``` and I created an extension Method like this : ``` public static class DogExt { public static string BarkYourName(this Dog dog) { return dog.Name + "!!!"; } } ``` Is there any way how to bind result of the `BarkYourName` method to a wpf component? Basically : is there any way hwo to bind it to an extension method?