Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define converter for binding inline (without resource)?

Tags:

c#

.net

wpf

xaml

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}" />
like image 671
Poma Avatar asked Jul 23 '11 09:07

Poma


People also ask

How do I bind a converter?

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.

What is a Converter in XAML?

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).


2 Answers

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} ...}" .. />
like image 134
sellmeadog Avatar answered Oct 18 '22 19:10

sellmeadog


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.

like image 24
Pop Catalin Avatar answered Oct 18 '22 20:10

Pop Catalin