INotifyPropertyChanged doesnt work when updating data code behind

BitSmithy 1,976 Reputation points
2022-03-18T10:39:40.183+00:00

Hello,

I have such XAML:
<Grid>
<TextBox Header="AAAA" Width="120" Height="80" Text="{Binding Data, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</Grid>

and such code behind:

public sealed partial class MainPage : Page, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;


    private string data;
    public string Data
    {
        get { return data; }
        set
        {
            if (data != value && this.PropertyChanged != null)
            {
                data = value;
                this.PropertyChanged(this, new PropertyChangedEventArgs("Data"));
            }
            else
                data = value;
        }
    }

    public MainPage()
    {
        this.InitializeComponent();
        Data = "aaa";
    }
}

This code sets Data property as "aaa", this property is binded to TextBox
In my opinion when I run the app, there in TextBox should be visible value "aaa", but the TextBox is empty.

What I am doing wrong?

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. BitSmithy 1,976 Reputation points
    2022-06-02T13:39:21.243+00:00

    I found the problem.
    Probably when I tried to create INotifyPropertyChanged I misclicked the intelisense hint, and it creaded a new empty class INotifyPropertyChanged. I overlooked this.
    When I deleted this class, all started to work.

    1 person found this answer helpful.
    0 comments No comments

  2. Nico Zhu (Shanghai Wicresoft Co,.Ltd.) 12,861 Reputation points
    2022-03-21T02:15:59.127+00:00

    Hello,
    Welcome to Microsoft Q&A!

    INotifyPropertyChanged doesnt work when updating data code behind

    The problem is that you have not specific current DataContext when used Binding, For solving this problem you could specific current DataContext as this in MainPage ctor.

    public MainPage()  
    {  
        this.InitializeComponent();  
        this.DataContext = this;      
        Data = "aaa";  
    }  
    

    Or use x:Bind to replace Binding that could binding property in the code behind. For more detail please refer to Data binding in depth

    Nico.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.