I have TextBox:
<TextBox DockPanel.Dock="Bottom"
FontFamily="Consolas"
Text="{Binding Path=Output}"
VerticalScrollBarVisibility="Visible"
HorizontalScrollBarVisibility="Auto"
AcceptsReturn="True"
AcceptsTab="True" />
To inside this TextBox I want to send some/add the message:
public string Output { get; set; }
public void WriteToOutput(string message)
{
Output += DateTime.Now.ToString("dd.MM HH:mm:ss") + " " + message + Environment.NewLine;
}
public void LoadExcelFile()
{
WriteToOutput("Start....")
//SOME CODE
WriteToOutput("End....")
}
Output should looks like:
Start...
End...
But the text it's not showing into TextBox. What is the reason?
Update: my MainViewModel.cs:
[AddINotifyPropertyChangedInterface]
public class MainViewModel
{
....
}
I'm using PropertyChanged.Fody
You're missing the INotifyPropertyChanged
implementation.
A working example:
using System.ComponentModel;
public partial class MainWindow : Window, INotifyPropertyChanged
{
private string output;
public string Output
{
get { return output; }
set
{
output = value;
OnPropertyChanged(); // notify the GUI that something has changed
}
}
public MainWindow()
{
this.DataContext = this;
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Output = "Hallo";
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName: propertyName));
}
}
}
The XAML code would look like this:
<TextBox Text="{Binding Output}"/>
As you can see, whenever the Output
property changes, the PropertyChanged
event will be called. Every GUI Element that is bound to that Property will know that something has changed.
Note: [CallerMemberName]
automatically gets the name of the property the method has been called with. If you don't want to use it, remove it. You'd have to change the OnPropertyChanged
call to OnPropertyChanged("Output");
, though.