我有TextBox:
<TextBox DockPanel.Dock="Bottom"
FontFamily="Consolas"
Text="{Binding Path=Output}"
VerticalScrollBarVisibility="Visible"
HorizontalScrollBarVisibility="Auto"
AcceptsReturn="True"
AcceptsTab="True" />
在这个TextBox内部我想发送一些/添加消息:
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....")
}
输出应如下所示:
Start...
End...
但它没有显示在TextBox中的文本。是什么原因?
更新:我的MainViewModel.cs:
[AddINotifyPropertyChangedInterface]
public class MainViewModel
{
....
}
我正在使用PropertyChanged.Fody
你错过了INotifyPropertyChanged
实现。
一个工作的例子:
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));
}
}
}
XAML代码如下所示:
<TextBox Text="{Binding Output}"/>
如您所见,每当Output
属性发生变化时,都会调用PropertyChanged
事件。绑定到该属性的每个GUI元素都将知道某些内容已更改。
注意:[CallerMemberName]
会自动获取调用该方法的属性的名称。如果您不想使用它,请将其删除。但是,您必须将OnPropertyChanged
调用更改为OnPropertyChanged("Output");
。