Alan2
Alan2

Reputation: 24602

How can I bind the value of a field to a label in Xamarin?

Here is what I tried. Note that I removed parts of the XAML to make the question shorter but I tested it out by setting detailx.text in my cs and when I do it that way it displays XXXX:

<Frame x:Class="Japanese.PhrasesFrame">
    <StackLayout x:Name="phrasesFrameStackLayout" >
        <Grid x:Name="phraseGrid">
            <Grid x:Name="wordGrid" >
                <Grid x:Name="detailGrid">
                   <Label x:Name="detail1" Text="{Binding English}" XAlign="Center" />
                   <Label x:Name="detailx" XAlign="Center" />

In my CS I have

    public PhrasesFrame()
    {
        InitializeComponent();
        correctButton.Clicked += correctButtonClicked;
        resetButton.Clicked += resetButtonClicked;
        SetBindings();
        wordGrid.BindingContext = AS.phrase;
    }

In a method I have this:

public partial class PhrasesFrame : Frame
{
    Random rand = new Random();

    public PhrasesFrame()
    {
        InitializeComponent();
        wordGrid.BindingContext = AS.phrase;
        AS.phrase = new PSCViewModel() { English = "abcd" };
        this.detailx.Text = "XXXX";
    }

My problem is that when I used Binding English then the label never shows the text abcd but I do see the XXXX

Can someone tell me if I am missing something obvious. I tried everything but no success.

Upvotes: 1

Views: 63

Answers (1)

Gerald Versluis
Gerald Versluis

Reputation: 34128

Try changing the order, like this:

AS.phrase = new PSCViewModel() { English = "abcd" };
wordGrid.BindingContext = AS.phrase;

Whenever you set the BindingContext at that moment it is applied, as is. If you make changes afterwards, you can, but you need to implement the INotifyPropertyChanged event to fire off a signal to the UI indicating which property has changed. Only then will it be update in the UI.

Upvotes: 2

Related Questions