gpt4 book ai didi

C# : public observablecollection instance pass items to protected observablecollection

转载 作者:行者123 更新时间:2023-12-03 10:28:10 27 4
gpt4 key购买 nike

我有以下类(class),效果很好

public class RemoteSource {
ObservableCollection<RemoteDataViewModel> remote;
string[] _servers = new string[] {
"server",
"server",
"server",
"server",
"server"
};
public RemoteSource() {
remote = CreateDataSource();
}
protected ObservableCollection<RemoteDataViewModel> CreateDataSource() {
ObservableCollection<RemoteDataViewModel> res = new ObservableCollection<RemoteDataViewModel>();
ITerminalServicesManager _manager = new TerminalServicesManager();
foreach (var host in _servers) {
using (ITerminalServer srv = _manager.GetRemoteServer(host)) {
try {
srv.Open();
foreach (ITerminalServicesSession session in srv.GetSessions()) {
res.Add(new RemoteDataViewModel() { Server = srv.ServerName, SessionID = session.SessionId, UserID = session.UserName, State = session.ConnectionState, ConnectedTime = session.ConnectTime, LogonTime = session.LoginTime, IdleTime = session.IdleTime, UserIP = session.ClientIPAddress, Workstation = session.WindowStationName });
}
srv.Close();
}
catch (Win32Exception) { }
catch (SystemException) { }
catch (Exception) { }
}
}
return res;
}
/// <summary>
/// Gets the data.
/// </summary>
/// <value>
/// The data.
/// </value>
public ObservableCollection<RemoteDataViewModel> Data { get { return remote; } }
public ObservableCollection<string> hosts { get; set; }
}

RemoteSource 已设置,但按钮事件执行以下操作
DataContext = new RemoteSource();

我想通读一个文本文件,其中包含这样的服务器名称列表
Server1
Server2
Server3
etc

并将它们加载到 ObservableCollection 中然后能够做我目前在这条线上做的同样的事情
foreach (var host in _servers) # but where _servers is the observablecollection initiated from the button event

我试图在按钮事件下做这样的事情,但 rs.hosts 总是返回为 null
RemoteSource rs = new RemoteSource();
rs.hosts.Add(Environment.MachineName);

最佳答案

您的 ObservableCollection<T>应该是您的 ViewModel 的属性。然后,在 View 中,绑定(bind)一些 ItemsControl.ItemsSource属性(property)给它。

例如( super 简化):

public class SessionViewModel : INotifyPropertyChanged
{
// ...

public ObservableCollection<String> ServerList { get; set; }
}

在 View 中
<ListView x:Name="ServerList" ItemsSource="{Binding ServerList}"/>

关于C# : public observablecollection<ViewModel> instance pass items to protected observablecollection<ViewModel>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27197955/

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