我有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
答案 0 :(得分:5)
您缺少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");
。