Search code examples
c#xamluwptwo-way-bindingxbind

x:Bind TwoWayBinding not working on Textblock


I am trying to make the two way binding work on Textblock with compilation binding x:Bind

Problem: Even though setting TwoWay bind mode and PropertyChanged source trigger. Can not get it to work. When the object property balance changed in code behind it does not get updated in UI.

Below is the code.

XAML

<TextBlock  x:Name="Balance"
            Text="{x:Bind classObject.Balance,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

Code-Behind

private ClassName classObject = new ClassName() { Name = "Foo",Balance = 100 };
public Observable ViewModel { get; } = new Observable();
private void NavLinksList_ItemClick(object sender,ItemClickEventArgs e)
{
    classObject = new ClassName() { Name = "Blah",Balance = 10 * new Random().NextDouble() * (50 - 1) + 1 };
}

Observable

public class Observable : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
    {
        if (Equals(storage, value))
        {
            return;
        }

        storage = value;
        OnPropertyChanged(propertyName);
    }

    protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Alternate solution

Set Textblock.Text in code behind manually.

But the issue is property changed event is supposed to work and automatically update the text block without explicit coding.

I searched other questions , but couldnt find the similar one.


Solution

  • If you want to update the data-bound Text property of the TextBlock you should set the source property that it's bound to, i.e. the Balance property of classObject. Also note that the ClassName class should implement the INotifyPropertyChanged interface and raise change notifications.

    Setting the classObject field to a new instance of a ClassName is not supposed to update the TextBlock, unless you call Bindings.Update() afterwards.