我想在网格视图中将byte []绑定到差异标签,但是当我在计时器事件中更改值时,它很奇怪,onPropertyChanged()不会调用,结果标签没有' t用byte []更新。请帮我解决我的代码中的错误。我可以用我列出的代码绑定一个字节,但似乎无法使用byte []。谢谢!
System.Timers.Timer testtimer;
Grid gridView;
byte[] _recvdata;
byte testbyte;
public byte[] RecvData
{
get
{
return _recvdata;
}
set
{
if (_recvdata != value)
{
_recvdata = value;
OnPropertyChanged("RecvData");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected override void OnPropertyChanged(string propertyName)
{
var changed = PropertyChanged;
if (changed != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public DevicePage(IDevice currDevice)
{
device = currDevice;
this.Title = "Status";
testtimer = new System.Timers.Timer();
testtimer.Interval = 1000;
testtimer.Elapsed += OnTimedEvent;
testtimer.Enabled = true;
gridView = new Grid();
RecvData = new byte[40];
for (byte i = 0; i < 40;i++)
{
string st;
var lb = new Label ();
st = "RecvData[" + i + "]";
lb.SetBinding(Label.TextProperty, st);
lb.BindingContext = this;
gridView.Children.Add(lb, 0, i);
}
this.Content = gridView;
}
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
byte i;
testbyte += 1;
for (i = 0; i < 40; i++)
{
RecvData[i] = testbyte;
}
}
答案 0 :(得分:0)
当您使用[indexer]更改它时,不会调用RecvData属性的setter。您有两种选择:
1)使用索引器更改字节数组后手动调用OnPropertyChanged:
private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
byte i;
testbyte += 1;
for (i = 0; i < 40; i++)
{
RecvData[i] = testbyte;
}
OnPropertyChanged("RecvData");
}
2)为字节数组创建一个包装器,当你使用索引器更改数组时会自动调用OnPropertyChanged:
public class ByteArrayWrapper : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
byte[] _array;
public byte[] Array
{
get
{
return _array;
}
set
{
if (_array != value)
{
_array = value;
OnPropertyChanged("Array");
}
}
}
public byte this[int index]
{
get
{
return _array[index];
}
set
{
_array[index] = value;
OnPropertyChanged("Array");
}
}
protected void OnPropertyChanged(string propertyName)
{
var changed = PropertyChanged;
if (changed != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
然后而不是像你这样操作你的字节数组:
public byte[] RecvData
{
// get/set
}
你应该使用上面一个类的实例:
public ByteArrayWrapper RecvData
{
// get/set
}
其他代码应该没问题。如果绑定不起作用,可能您需要绑定到RecvData.Array [i]而不是RecvData [i],请告诉我这是否有效,因为我无法测试现在。