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?
Do you want to binding a string value to a int attribute? For example, You have a attribute called MyProperty like following code.
MyProperty
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).
HeightRequest
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.
100
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.
<ContentPage.Resources> <ResourceDictionary> <local:StringToIntConverter x:Key="StringToInt"/> </ResourceDictionary> </ContentPage.Resources> <StackLayout> <Label Text="{Binding MyProperty}" x:Name="myLabel" ></Label> <Label BackgroundColor="Blue" HeightRequest="{Binding MyProperty,Converter={StaticResource StringToInt}}" /> </StackLayout>
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.
@johnstinelol Your binding way is ok, you can binding it directly, Just add public int MyProperty { get; set; } like following code.
public int MyProperty { get; set; }
public partial class MainPage : ContentPage { public int MyProperty { get; set; } public MainPage() { InitializeComponent(); MyProperty = 1; this.BindingContext = this; } }
Answers
Do you want to binding a string value to a int attribute? For example, You have a attribute called
MyProperty
like following code.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.When I use it in the xaml.
Something like that but where the text property on the label is binding to an int in the code behind.
XAML:
c#:
If this is a really bad example I apologize. I'm very new to the world of Xamarin.
@johnstinelol Your binding way is ok, you can binding it directly, Just add
public int MyProperty { get; set; }
like following code.