发生的情况是,如果字符串相同,它不会在 WPF 表单文本框中打印/绑定/发布到视图。例如,如果我使用 random 来生成我正在制作成字符串的字节数组,那么它确实会发布到视图中。
这是视图绑定到的我的 ViewModel:
public class ViewModel : INotifyPropertyChanged
{
public StringBuilder Data
{
get { return _data; }
set
{
_data = value;
OnPropertyChanged("Data");
}
}
private Service service = new Service();
private StringBuilder _data;
public ViewModel()
{
service.BytesArrived += ServiceOnBytesArrived;
ThreadPool.QueueUserWorkItem(starupService);
}
private void starupService(object state)
{
service.Start();
}
private void ServiceOnBytesArrived(byte[] bytes)
{
var sBuilder = new StringBuilder();
foreach (var b in bytes)
{
sBuilder.Append(b.ToString() + ", ");
}
Data = sBuilder;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
这是只为我打印字节的服务(如果使用 random 则可以正常工作:
public class Service
{
public void Start()
{
var random = new Random(DateTime.Now.Minute);
while (true)
{
//random.NextBytes(bytes);
for (int i = 0; i < 10; i++)
{
bytes[i] = 0;
Thread.Sleep(10);
}
//Thread.Sleep(100);
BytesArrived(bytes);
}
}
private byte[] bytes = new byte[10];
public event Action<byte[]> BytesArrived;
}
这是我正在使用的使用 AppendText 的依赖属性:
public static class TextBoxAttachedBehaviors
{
#region AppendText Attached Property
public static string GetAppendText(TextBox textBox)
{
return (string)textBox.GetValue(AppendTextProperty);
}
public static void SetAppendText(
TextBox textBox, string value)
{
textBox.SetValue(AppendTextProperty, value);
}
public static readonly DependencyProperty AppendTextProperty =
DependencyProperty.RegisterAttached(
"AppendText",
typeof(string),
typeof(TextBoxAttachedBehaviors),
new UIPropertyMetadata(null, OnAppendTextChanged));
private static void OnAppendTextChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
if (e.NewValue == null)
return;
TextBox textBox = d as TextBox;
textBox.AppendText(e.NewValue.ToString());
}
#endregion
}
XAML:
<TextBox attachedBehaviors:TextBoxAttachedBehaviors.AppendText="{Binding TextBoxAppend}"/>
如果你有 ReSharper,它会提供替换命名空间,例如attachedBehaviors:
用实际附加行为的类的链接,在我的例子中是xmlns:attachedBehaviors="clr-namespace:Support.NetworkMonitor.AttachedBehaviors"
.