[英]Can't get TextBox to update OnPropertyChanged from string
使用该网站很长时间后,我终于确定了一个不断遇到的问题,这让我发疯。 我一直在使用WPF文本框显示我正在编写的程序的进度,因此我将其绑定到自定义日志。 但是:文本框不会更新。 我究竟做错了什么?
在MainWindow.xaml.cs中:
public MainWindow()
{
...
DataContext = this;
...
}
在MainWindow中。
<ScrollViewer Grid.Column="0" Grid.Row="2">
<TextBox Name="ErrorConsole" AcceptsReturn="true" TextWrapping="Wrap" Margin="0,3,10,0" TextChanged="Console_TextChanged" Background="Black" Foreground="White" />
</ScrollViewer>
并在Log.cs中
public class Log : INotifyPropertyChanged
{
private string _logText = "";
private static Log instance;
public static string filename { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public static Log GetInstance()
{
if (instance == null)
{
instance = new Log();
}
return instance;
}
public string logText
{
get
{
return _logText;
}
set
{
if (!(_logText == value))
{
_logText = value;
OnPropertyChanged(SystemStrings.status_Updated);
}
}
}
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
//Adds custom messages to the logfile
public void Add(string message)
{
logText += (message + "\n");
logText += SystemStrings.divider + "\n\n";
}
public void AddSimple(string message)
{
logText += (message + "\n");
}
//Cleans the log that is in memory
public void Clear()
{
logText = "";
}
}
当用户按下“开始”按钮时,将执行以下代码:
Binding binding = new Binding();
binding.Source = Log.GetInstance();
binding.Mode = BindingMode.TwoWay;
binding.Path = new PropertyPath(SystemStrings.status_Updated);
BindingOperations.SetBinding(ErrorConsole, TextBox.TextProperty, binding);
我已经尝试了绑定1路和2路,但是到目前为止还没有运气。 但是:如果我将其设置为2way并使用此代码
private void Console_TextChanged(object sender, TextChangedEventArgs e)
{
ErrorConsole.Text = Log.GetInstance().logText;
}
键入单个字符后,文本框(ErrorConsole)实际上将更新为正确的文本。
在这里的任何帮助将不胜感激,因为正是那些细小的东西使程序得以完善,尽管我认为它不是图形上最先进的程序,但至少应该使用一些不错的工具。
-彼得
事实证明,没有适当的方法可以做到这一点,但是我设法通过玩一个(不是那么整齐地使用)Observable Collection来解决这个问题。 感谢大家的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.