Forum Xamarin Xamarin.Forms

I want to know how to bind value to a label without clicking a button from code behind

FlaveFlave Member ✭✭
        this is my code so far

                Label displayLabel;
                Button backspaceButton;
                public MyCalculator ()
                {
                        App app = Application.Current as App;
                        if(app.DisplayLabelText != null)
                        {

                            displayLabel.Text = app.DisplayLabelText;
                            backspaceButton.IsEnabled = displayLabel.Text != null && displayLabel.Text.Length > 0;
                        }
                }

Best Answer

Answers

  • JarvanJarvan Member, Xamarin Team Xamurai

    @Flave

    how to bind value to a label without clicking a button

    What do you mean 'bind value to a label without clicking a button', could you tell more details?

  • FlaveFlave Member ✭✭

    @yelinzh

    I meant how to assign values to the label like I have done here
    displayLabel.Text = app.DisplayLabelText;
    displayLabel.Text is not accepting the value from app.DisplayLabelText

  • JoeMankeJoeManke USMember ✭✭✭✭✭
    edited July 2019

    @Flave said:

    Label displayLabel;
    Button backspaceButton;
    public MyCalculator ()
    {
        App app = Application.Current as App;
        if(app.DisplayLabelText != null)
        {
                        
            displayLabel.Text = app.DisplayLabelText;
            backspaceButton.IsEnabled = displayLabel.Text != null && displayLabel.Text.Length > 0;
        }
    }
    

    If this is your full, unredacted code, your problem is that you are not initializing the Label and Button and you're getting a NullReferenceException.

    After you fix that, you will probably want to read a tutorial or two about what "binding" actually means and implement it.

  • FlaveFlave Member ✭✭

    @JoeManke

    Ok not really the full code, though I tried saving Transient Data and its working perfectly, the app.DisplayLabelText is getting value from data saved when app resumes, but displayLabel.Text is not receiving the data when i assign like this
    displayLabel.Text = app.DisplayLabelText;
    So please is there any other way i could have assigned value from app.DisplayLabelText to displayLabel.Text

  • NMackayNMackay GBInsider, University admin
    edited July 2019 Accepted Answer

    Yes, you can use relative source binding to do it in XAML by having one label's text bind to the the other labels value (assuming you give them names)

    https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-binding-basics

Sign In or Register to comment.