【发布时间】:2021-05-06 21:18:09
【问题描述】:
我有这样的程序类:
class Program
{
public static UDProtocol MyUdp;
private static readonly int Port = 11000;
public static F_Main F1;
public static BindingSource DtgvSource;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
OnStart();
Application.Run();
}
private static void OnStart()
{
MyUdp = new UDProtocol(Port);
F1 = new F_Main();
MyUdp.Start();
DtgvSource = new BindingSource(MyUdp.ClientList, null);
F1.DTGV_Clients.DataSource = DtgvSource;
}
}
我的 UDProtocol 看起来像这样(简化):
public class UDProtocol
{
private readonly UdpClient UdpMe;
private readonly int Port;
private Client CurrentClient;
public BindingList<Client> ClientList { get; set; }
public UDProtocol(int _port)
{
Port = _port;
UdpMe = new UdpClient(Port);
ClientList = new BindingList<Client>();
}
public void Start()
{
ThrFlag = true;
new Thread(() =>
{
while (ThrFlag)
{
if (UdpMe.Available > 0)
{
try
{
NewClientEP = new IPEndPoint(IPAddress.Any, Port);
string data = Encoding.UTF8.GetString(UdpMe.Receive(ref NewClientEP));
CurrentClient = new Client
{
Name = Dns.GetHostEntry(NewClientEP.Address).HostName,
IP = NewClientEP.Address,
};
MsgObj NewMsg = new MsgObj(data) { From = CurrentClient };
AnalyseMessage(NewMsg);
}
catch { }
}
Thread.Sleep(1);
}
}).Start();
}
public void AnalyseMessage(MsgObj msg)
{
//some useless code
msg.From.Connected = true;
}
}
我也有一个 MsgObj 类:
public class MsgObj
{
//some others variables
private Client _From {get; set;}
public MsgObj(string data)
{
//some useless code
}
}
以及实现INotifyPropertyChanged
的客户端类 public class Client : INotifyPropertyChanged
{
public IPAddress IP { get; set; }
private bool _connected;
public event PropertyChangedEventHandler PropertyChanged;
public bool Connected
{
get => _connected;
set
{
_connected = value;
NotifyPropertyChanged("Connected");
}
}
private void NotifyPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
在我的 F1 (F_Main) 中,我的 Datagridview 是这样构建的:
public F_Main()
{
InitializeComponent();
DTGV_Clients.AutoGenerateColumns = false;
DTGV_Clients.Columns[0].DataPropertyName = "Connected";
DTGV_Clients.Columns[1].DataPropertyName = "IP";
}
当我将客户端添加到 ClientList (BindingList) 时,datagridview 会更新。另一方面,当我尝试修改客户端的“已连接”属性时,尽管我实现了 INotifyPropertyChanged 接口,但它并未在 Datagridview 中更新。
我也试过ResetBinding(false)
分析数据()
但没有成功。
尽管我对这个主题进行了所有研究,但我看不出我做错了什么以及它可能来自哪里。
【问题讨论】:
标签: c# datagridview datasource