我需要在DataGrid中显示从外部源接收到的一组位状态。为此,我使用像这样的ObservableCollection
for epoch in range(EPOCHS):
for data, target in data_a:
output = model(data)
loss = criterion(output, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
for data, target in data_b:
output = model(data)
loss = criterion(output, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
for data, target in data_c:
output = model(data)
loss = criterion(output, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
public class UpdateIO : INotifyPropertyChanged
我的IObitDetails类是
public static ObservableCollection<IObitDetails> PlcCommonOutputs = new ObservableCollection<IObitDetails>();
接下来,我创建了收藏集</ p>
public class IObitDetails : INotifyPropertyChanged
{
bool _bitValue;
public string BitGroup { get; set; }
public string BitText { get; set; }
public short CIOaddress { get; set; }
public short BitPosition { get; set; }
public bool BitValue
{
get { return _bitValue; }
set { SetField(ref _bitValue, value); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value,
[CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
public IObitDetails(string bg, bool bv, string bt, short adr, short pos)
{
BitGroup = bg;
BitValue = bv;
BitText = bt;
CIOaddress = adr;
BitPosition = pos;
}
}
这里的BitPositions声明为:
PlcCommonOutputs.Add(new IObitDetails("CO", oCommonOpLampRed,"Op. Red", 0x0001, obitCommonOpLampRed));
PlcCommonOutputs.Add(new IObitDetails("CO", oCommonOpLampGreen,"Op. Green", 0x0001, obitCommonOpLampGreen));
PlcCommonOutputs.Add(new IObitDetails("CO", oCommonMuteA,"MuteA", 0x0001, obitCommonMuteA));
PlcCommonOutputs.Add(new IObitDetails("CO", oCommonMuteB,"MuteB", 0x0001, obitCommonMuteB));
...
每个位都是一个属性,当我(在轮询线程中)读取端口并存储在oCommonOutputsPost中时会对其进行修改:
private const short obitCommonOpLampRed = 0;
private const short obitCommonOpLampGreen = 1;
private const short obitCommonMuteA = 2;
private const short obitCommonMuteB = 3;
...
每当我读取一个新的端口值时,这些位就会被设置/重置(我看到正确修改了位属性)。 但是ObservableCollection(PlcCommonOutputs)不变。 如果我在调试器中手动更改集合中相应的BitValue,则它们会在UI中显示(因此,我不包含任何xaml)。 有没有办法在不增加代码复杂性的情况下完成此工作?
答案 0 :(得分:0)
一个简单的解决方法是,在设置器中增加要更改的属性值。例如:
private bool _oCommonMuteA;
public bool oCommonMuteA
{
get { return _oCommonMuteA; }
set
{
SetField(ref _oCommonMuteA, value);
OnPropertyChanged(nameof(oCommonMuteA));
}
}