Daniel Santos
Daniel Santos

Reputation: 15818

How to force View to update bound properties in Xamarin Forms?

I would like to force an databound property update in a content page. In this case is the ContentPage Title parameter.

<ContentPage x:Class="Containers.Views.ContainerPage" 
         xmlns="http://xamarin.com/schemas/2014/forms" 
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         Title="{Binding SomeStringProperty}"
         Appearing="ContentPage_Appearing">

The closest i get is this, but it does not works.

    private void ContentPage_Appearing(object sender, EventArgs e)
    {
        this.BindingContext = null;
        this.BindingContext = myClassInstance;
    }

I would not like to implement onPropertyChange events. I Just want to "refresh" the bounded data of a view.

Upvotes: 2

Views: 4736

Answers (2)

rubens.lopes
rubens.lopes

Reputation: 2535

A way that worked for me with CustomView is:

using Xamarin.Forms;

namespace Xam.CustomViews.ContentsViews
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class FeatherButton : ContentView
    {
        // ... Existing code ...

        public FeatherButton()
        {
            InitializeComponent();
            PropertyChanged += OnPropertyChanged;
        }

        private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == StyleProperty.PropertyName)
            {
                UpdateVisualProperties();
            }
        }

        private void UpdateVisualProperties()
        {
            OnPropertyChanged(nameof(TextColor));
            OnPropertyChanged(nameof(BackgroundColor));
            OnPropertyChanged(nameof(BorderColor));
            OnPropertyChanged(nameof(BorderWidth));
        }

        // ... Existing code ...
    }
}

Upvotes: 0

Sharada
Sharada

Reputation: 13601

If your viewmodel already implements INotifyPropertyChanged - you can try raising PropertyChangedEvent with null/empty parameter - that should force an update for all bound properties - more details here.

public void RaiseAllProperties()
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(null));
}

Upvotes: 7

Related Questions