Moto
Moto

Reputation: 1141

ValueConverter - binding to self

I need to bind a label to a composite value - made up of a couple of values in the model. I'm trying to use a ValueConverter to do so, but I can't figure out how to pass the object itself to the ValueConverter. Here's my code: in XAML:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:MyApp;assembly=MyApp"
         x:Class="MyApp.SavedDetailsPage">
  <ContentPage.Resources>
      <ResourceDictionary>
          <local:DetailsConverter x:Key="detailsCvt" />
      </ResourceDictionary>
  </ContentPage.Resources>
  ...
    <Label Text="{Binding ???, Converter={StaticResource detailsCvt}}" FontSize="Small" TextColor="Gray" />
  ...

in DetailsConverter.cs:

class DetailsConverter : IValueConverter
{
    object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        MyModel myModel = (MyModel)value;
        return (myModel.FirstName + " " + myModel.LastName);
    }
    ...

I tried using '.' for binding to self, but that didn't work.

I found a way around it by adding a .This property to MyModel, that gives access to the object itself, so I can pass 'This' in the XAML binding, but not sure if that's the best way.

Thanks in advance!

Upvotes: 1

Views: 1674

Answers (1)

Stephane Delcroix
Stephane Delcroix

Reputation: 16222

to bind to the ViewModel, you can use one of the following syntax

{Binding}
{Binding .}
{Binding Path="."}

Upvotes: 6

Related Questions