Is it possible to define type converter for binding inline (without resource)?
Something like this:
<Button Visibility="{Binding ElementName=checkBox, Path=IsChecked, Converter={new BooleanToVisibilityConverter}" />
Create a converter by implementing the IValueConverter interface and implementing the Convert method. That method should return an object that is of the same type as the dependency property that the binding targets, or at least a type that can be implicitly coerced or converted to the target type.
In this article, I'm going to show you how you can use value converter in XAML to convert one format of data into another format. In our case, we'll convert a string value (value in the textbox) to a Boolean value (checked status of a checkbox).
You can create and expose your converter through a custom MarkupExtension
which will give you the inline declaration you're looking for:
public class BooleanToVisibilityConverterExtension : MarkupExtension, IValueConverter
{
private BooleanToVisibilityConverter converter;
public BooleanToVisibilityCoverterExtension() : base()
{
this.converter = new BooleanToVisibilityConverter();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return this.converter.Convert(value, targetType, parameter, culture);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return this.converter.ConvertBack(value, targetType, parameter, culture);
}
}
Now you can use the MarkupExtension inline to create a new converter:
<Button Visibility="{Binding Converter={local:BooleanToVisibilityConverter} ...}" .. />
It's not possible using binding syntax. But it is possible using element syntax:
<Button.Visibility>
<Binding ElementName="checkBox" Path=IsChecked>
<Binding.Converter>
<BooleanToVisibilityConverter />
</Binding.Converter>
</Binding>
</Button.Visibility>
But why would you want to do this? It would mean every binding instance will create a new converter. That's not efficient from a memory point of view.
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