gpt4 book ai didi

c# - 为什么当字符串相等时此 AppendText 依赖属性不打印?

转载 作者:太空宇宙 更新时间:2023-11-03 13:51:14 26 4
gpt4 key购买 nike

如果字符串相同,则不会打印/绑定(bind)/发布到 WPF 表单文本框中的 View 。例如,如果我使用 random 来生成我正在制作成字符串的字节数组,那么它确实会发布到 View 中。

这是 View 绑定(bind)到的我的 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));
}
}

这是为我打印字节的服务(如果使用随机代替则工作正常:

   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,它将提供替换 namespace 的功能,例如attachedBehaviors: 带有实际附加行为的类链接,在我的例子中是 xmlns:attachedBehaviors="clr-namespace:Support.NetworkMonitor.AttachedBehaviors"

最佳答案

DependencyProperties 在触发通知之前比较它们的旧值和新值,并且仅在确实存在差异时才触发它。解决方案很简单:在设置字符串之前将 AppendText 设置为 null,例如

  public StringBuilder Data
{
get { return _data; }
set
{
_data = null;
OnPropertyChanged("Data");
_data = value;
OnPropertyChanged("Data");
}
}

关于c# - 为什么当字符串相等时此 AppendText 依赖属性不打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13631633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com