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?
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.
Programming is the logical IQ game.
Binding with MethodName is not possible in WPF as the Binding engine only works with Properties. Although, you can use some tricks.
Here are some ways to accomplish this.
Add an extension method to the get
accessor of the property, like this
private string _name;
public string Name
{
get { return _name.BarkYourName(); }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
Add a converter to change the effect of the Name property, like this
public class NameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return "!!!";
return value.ToString().BarkYourName();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
public static class StringExt
{
public static string BarkYourName(this string str)
{
return str + "!!!";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With