Search code examples
c#wpfinotifypropertychanged

INotifyPropertyChanged only updates UI when method exists


I need to update the UI within the method Button_Click.

when i place a break stop after Test = "sss"; the ui does not update but when I continue until the method finished it updates the UI.

this is a simple scenario for demo only, but in another example I have a for loop that is assessing a long list of objects so there are several updates throughout the assessment of the for loop.

how can the ui be updated within the method and not wait until the end....

xaml

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding Path=Test}"></TextBox>
            <Button Click="Button_Click">Click</Button>
        </StackPanel>
    </Grid>
</Window>

MainWindow.xaml.cs

public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

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


        private string test;
        public string Test { get { return test; } set { test = value; OnPropertyChanged("Test"); } }


        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            Test = "aaa";
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Test = "sss";
            //do other stuff here
        }
    }

Solution

  • let's use an async method, see example:

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
    
      Test = "sss";
      // text box updated immediately via property Test
    
      await Task.Delay(5000); // wait 5 sec.
    
      Test = "ttt";
      // after 5 sec. updated again
    }