Skip to content

ConverterProxy en

Leksiqq edited this page Jun 7, 2024 · 4 revisions

Attention! This article, as well as this announcement, are automatically translated from Russian.

ConverterProxy class

an adapter that is a MarkupExtension for IValueConverter or IMultiValueConverter converters, which are not MarkupExtension and cannot become one, since they are already inherited from another type, but are required where MarkupExtension is expected.

Implements the IValueConverter and IMultiValueConverter interfaces.

Properties

  • public IValueConverter? Converter {get; set;} - DependencyProperty containing, if assigned, a reference to a real converter that implements the IValueConverter interface.
  • public IValueMultiConverter? MultiConverter {get; set;} - DependencyProperty containing, if assigned, a reference to a real converter that implements the IValueMultiConverter interface.

Example

Consider a situation where we want to use a descendant of the UserControl class as a converter in order to somehow use its internal state. At the same time, we cannot set {Binding ...} in the Converter property of the Binding type. The ConverterProxy class helps solve this problem.

In the MyControl.xaml file:

<UserControl
    x:Class="MyControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:l="clr-namespace:Net.Leksi.WpfMarkup;assembly=Net.Leksi.WpfMarkupExtension"
    x:Name="mc"
    >
    <UserControl.Resources>
        <ResourceDictionary>
            <l:ConverterProxy Converter="{Binding ElementName=mc}" x:Key="Converter"/>
        </ResourceDictionary>
    </UserControl.Resources>
    <StackPanel>
        <TextBox Text="{Binding Value, Converter={StaticResource Converter}"/>
    </StackPanel>
</UserControl>

In the MyControl.xaml file:

public partial class MyControl: UserControl, IValueConverter
{
    public string Value
    {
        get
        {
            ...
        }
        set
        {
            ...
        }
    }
    ...
    public MyControl()
    {
        InitializeComponent();
    }
    ...
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        ...
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        ...
    }
}

Before: (BoolExpressionConverter) Start:(Overview) Next:(Demo)