Pramus
Pramus

Reputation: 430

C# Universal App - Data binding on click

I'm having trouble with data binding in an Universal App. Here's the binding:

<TextBlock x:Name="textBlockOutput" Text="{x:Bind ViewModel.textBlockValue, Mode=TwoWay}" />

When I initialise the app, data binding works perfectly fine and the textBlock item gets the value of assigned field:

 public MainPage()
    {
        this.InitializeComponent();
        this.ViewModel = new MainViewModel();
        ViewModel.textBlockValue = "Click the button";
    }

Unfortunately when I click the button, value of the textBlock is not being updated. When I debug the app I can see that the function below is called but it makes no change to the textBlock.

private void waitBtnClicked(object sender, RoutedEventArgs e)
{
    ViewModel.textBlockValue = "Clicked";
    SomeMethod();
}

Any clues?

Upvotes: 2

Views: 509

Answers (1)

Mykola
Mykola

Reputation: 3363

You will need to specify property which can be observed by View. So you must implement your ViewModel from INotifyPropertyChanged and INotifyPropertyChanging interfaces. Than build your ViewModel class as folows:

class MainWindowViewModel : INotifyPropertyChanged, INotifyPropertyChanging
{
    private string textBlockValue;

    public string TextBlockValue
    {
        set
        {
            if (textBlockValue != value)
            {
                OnPropertyChanging("TextBlockValue");

                textBlockValue = value;

                OnPropertyChanged("TextBlockValue");
            }
        }
        get
        {
            return textBlockValue;
        }
    }
    ///////////////////////////////////////////////////////

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    #region INotifyPropertyChanging Members

    public event PropertyChangingEventHandler PropertyChanging;

    #endregion

    public void OnPropertyChanging(string propertyName)
    {
        if (PropertyChanging != null)
            PropertyChanging.Invoke(this, new PropertyChangingEventArgs(propertyName));
    }

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Than bind to your XAML:

<TextBlock x:Name="textBlockOutput" Text="{x:Bind ViewModel.TextBlockValue, Mode=TwoWay}" />

So you just must only assign the value throw the property to enable UI autoupdate.

Upvotes: 1

Related Questions