【发布时间】:2013-10-30 09:10:55
【问题描述】:
在使用这个网站很长一段时间后,我终于确定了一个我一直遇到的问题,这让我发疯了。我一直在使用 WPF 文本框来显示我正在编写的程序的进度,因此我已将其绑定到自定义日志。但是:文本框不会更新。我做错了什么?
在 MainWindow.xaml.cs 中:
public MainWindow()
{
...
DataContext = this;
...
}
在主窗口中。
<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-way 和 2-way,但到目前为止没有运气。但是:如果我将其设置为 2way 并使用此代码
private void Console_TextChanged(object sender, TextChangedEventArgs e)
{
ErrorConsole.Text = Log.GetInstance().logText;
}
文本框 (ErrorConsole) 实际上会在您键入单个字符后立即更新为正确的文本。
这里的任何帮助都将不胜感激,因为正是这些小东西完善了程序,尽管它不是图形最先进的程序,但在我看来至少应该使用得不错。
-彼得
【问题讨论】:
-
静态成员与
this无关,因此当您调用PropertyChanged(this,...)时,它不适用于静态属性。 -
感谢您的回答,但是您建议将其绑定到什么?
-
作为一个肮脏的黑客,您可以使您的属性非静态,并且您的属性返回的成员是静态的,呃。我不敢相信我这么说。最好完全避免使用 UI 的静态。
-
我可能只是一个没有经验的程序员,或者只是没有我的一天,但你到底是怎么想的?