user10466538
user10466538

Reputation:

WPF binding does not work if function is triggered by a button

If the function is triggered by a Button the databinding doen't not work. If I call the same function on the MainWindow init it works. Anyone has any idea how to fix it? If I click on the button in debug mode I can clearly see that the SampleString property has changed as expected. Why can't I see the change in the TextBlock?

Mainwindow.xaml.cs:

using System;
using System.Windows;


namespace DTC_client_WPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public string SampleString { get; set; }

        public MainWindow()
        {
            SampleString = string.Empty;
            InitializeComponent();
            DataContext = this;
            Button_Click(null, null);
        }
        private void Print(string str)
        {
            SampleString += DateTime.Now + "|" + str + "\n";
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Print("Clicked");
        }
    }
}

XAML:

<Window x:Class="DTC_client_WPF.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:DTC_client_WPF"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="2*"/>
        </Grid.RowDefinitions>

        <ScrollViewer Grid.Row="1">
            <TextBlock x:Name="WPFConsole" ScrollViewer.VerticalScrollBarVisibility="Auto" Background="Black" Foreground="GreenYellow" Text="{Binding Path=SampleString, UpdateSourceTrigger=PropertyChanged}"  />
        </ScrollViewer>
        <Button Content="RUN" HorizontalAlignment="Left" Margin="24,41,0,0" VerticalAlignment="Top" Height="51" Width="76" FontSize="16" Click="Button_Click" Foreground="Black" Background="#FFB02626" BorderThickness="4,4,4,4"/>
    </Grid>
</Window>

This is the result no matter how often do I click on the "RUN" button. MainWindow result

Upvotes: 0

Views: 725

Answers (1)

Cheesebaron
Cheesebaron

Reputation: 24470

Bindings in WPF work through the INotifyPropertyChanged interface and its PropertyChanged event. If this event is not fired and not implemented by the DataContext, then the binding engine will not get notified the value was changed.

Upvotes: 1

Related Questions