简体   繁体   中英

Access Entry from ValueConverter

I need access to the entry component that the converter is attached to, so I can change the cursor position with Entry.CursorPosition .

I have a BindableObject that is also an IValueConverter, how can I get to the Entry

public class MaskConverter : BindableObject, IValueConverter
{

...

}

In XAML name the Entry and use x:Reference :

Converter with MyEntry property ( ConvertBack for Mode=TwoWay not shown):

public class MyConverter : BindableObject, IValueConverter
{
    public Entry MyEntry { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var entry = MyEntry;
        Debug.WriteLine($"convert:pos:{entry?.CursorPosition}:");
        return (string)value;
    }

    ...
}

XAML using MyEntry property ( MyText is a property on the viewmodel, not shown):

<ContentPage.Resources>
  <local:MyConverter x:Key="myConverter" MyEntry="{x:Reference myEntry}" />
  ...
</ContentPage.Resources>
...
<Entry x:Name="myEntry" Text="{Binding MyText, 
                                       Converter={StaticResource myConverter}}">

Without the MyEntry property the named Entry might be passed to the converter using ConverterParameter :

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var param = parameter as Entry;
    Debug.WriteLine($"convert:pos:{param?.CursorPosition}:");
    return (string)value;
}

XAML when passing the named Entry in ConverterParameter :

<ContentPage.Resources>
  <local:MyConverter x:Key="myConverter" />
  ...
</ContentPage.Resources>
...
<Entry x:Name="myEntry" Text="{Binding MyText, 
                                       Converter={StaticResource myConverter},
                                       ConverterParameter={x:Reference myEntry}}">

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM