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}" />
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.
You could do something like this. This should work.
Pseudocode :
public static class ConverterHost
{
public static readonly MyCoolConverter converter = new MyCoolConverter ();
}
and in the XAML, somethign like this:
{Binding Converter={x:Static conv:ConverterHost.converter }}
Hope this helps.
Regards.
No, you have to define the converter as a resource somewhere (window, usercontrol, etc.) before you can use it in a binding.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.