Share via


Is there a way to bind the text on a label to a variable(int) in the code behind?

Question

Monday, August 24, 2020 5:41 AM

I have been looking around for the past 2 days trying to find a way to bind the string on a label to a var but I haven't found anything yet. Is there something like that around? Or any alternative methods?

All replies (3)

Monday, August 24, 2020 7:53 AM

Do you want to binding a string value to a int attribute? For example, You have a attribute called MyProperty like following code.

public string MyProperty { get; set; } public MainPage() { InitializeComponent(); MyProperty = "100"; BindingContext = this; }

Then you want to bind this MyProperty to two controls, One is label's text(string), other is Label's HeightRequest(int).

If so, you can use ValueConverter to convert it like following code. For example, I convert the string value to int, then add 100 for testing.

``` class StringToIntConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { int valueConvet = int.Parse((string)value); return valueConvet+100; }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {

        return value;
    }
}

```

When I use it in the xaml. ```

    <Label Text="{Binding MyProperty}"  x:Name="myLabel" ></Label>
    <Label  BackgroundColor="Blue" HeightRequest="{Binding MyProperty,Converter={StaticResource StringToInt}}"  />


</StackLayout>

```


Monday, August 24, 2020 11:56 AM

Something like that but where the text property on the label is binding to an int in the code behind.

XAML: <Label Text="{Binding MyProperty}"/>

c#: ``` int MyProperty = 1;

```

If this is a really bad example I apologize. I'm very new to the world of Xamarin.


Tuesday, August 25, 2020 7:12 AM

@johnstinelol Your binding way is ok, you can binding it directly, Just add public int MyProperty { get; set; } like following code.

public partial class MainPage : ContentPage { public int MyProperty { get; set; } public MainPage() { InitializeComponent(); MyProperty = 1; this.BindingContext = this; } }