[英]Updating a datagridview when a datasource object property is changed C#
我有這樣的程序 class :
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 class:
public class MsgObj
{
//some others variables
private Client _From {get; set;}
public MsgObj(string data)
{
//some useless code
}
}
以及實現INotifyPropertyChanged的客戶端 class
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)
分析數據()
但沒有成功。
盡管我對這個主題進行了所有研究,但我看不出我做錯了什么以及它可能來自哪里。
我試圖更改與列表中的客戶端不同的currentclient 。 所以我輸入了AnalyzeData()
:
Client ThisClient = ClientList.FirstOrDefault(x => x.Name.Equals(msg.From.Name));
ThisClient.Connected = true;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.