C# 将WCF内容显示到列表框
我有一个WCF服务合同,该合同旨在通过TCP网络从剪贴板发送字符串,并由winform listbox接收和显示。我已成功连接了两个winforms,但我在获取要在listbox中显示的URL时遇到问题 app.config ApplicationService.cs WCF.cs(Winform)C# 将WCF内容显示到列表框,c#,winforms,wcf,C#,Winforms,Wcf,我有一个WCF服务合同,该合同旨在通过TCP网络从剪贴板发送字符串,并由winform listbox接收和显示。我已成功连接了两个winforms,但我在获取要在listbox中显示的URL时遇到问题 app.config ApplicationService.cs WCF.cs(Winform) 您可能会注意到,在ApplicationService.cs中,我使用WCF.listURL,这是因为我不知道如何正确调用表单listbox;ApplicationService中的listURL。
您可能会注意到,在ApplicationService.cs中,我使用WCF.listURL,这是因为我不知道如何正确调用表单listbox;ApplicationService中的listURL。正如我在评论中提到的,该服务除了请求数据或要执行的某些其他操作之外,不应该知道任何有关客户端的信息。我建议重写服务以仅返回数据,并让客户机应用程序将该数据绑定到
列表框
。但是,您需要删除IsOneWay
属性。大概是这样的:
[ServiceContract]
public interface IApplicationService
{
[OperationContract]
string GetURL();
}
在上面的代码中,单向属性被删除,该方法返回一个字符串
。我使用了字符串
而不是字符串数组
——客户端可以决定如何处理数据(拆分或不拆分、重新格式化等)
实现只是从剪贴板返回文本字符串
private void btnSendURL_MouseClick(object sender, EventArgs e)
{
ApplicationService url = new ApplicationService();
string data = url.GetURL();
listBox1.Items.AddRange(addCopy.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
最后,应用程序将调用服务方法并获取返回的数据。然后,它会将数据添加到
列表框
(示例中名为listBox1
)。现在,您已经将WCF服务与客户端分离,这是应该的。WinForm应用程序应该调用服务,服务应该返回数据,然后WinForm应该获取数据并将其绑定到控件。服务本身除了请求执行一个操作(方法)之外,应该对客户端一无所知。嗯,我明白你的意思了。我试过了,但它摆脱了我的P2P WCF表单连接,出于某种原因仍然没有向列表框添加内容。它不应该摆脱连接。如何添加连接?您可能还想编辑您的问题以包含相关的配置文件。好的,我已经更新了更多信息。也许你能更好地理解我现在想做什么。。。英雄联盟
public class ApplicationService : IApplicationService
{
public void GetURL()
{
var addCopy = Clipboard.GetText(TextDataFormat.Text);
WCF.listURL.Items.AddRange(addCopy.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
}
public static void WCF_Load(object sender, EventArgs e)
{
//Establish connection with Service
ServiceHost svc = new ServiceHost(typeof(ApplicationService));
svc.Credentials.Peer.MeshPassword = "hehe";
svc.Open();
//Both Server and Client binding should match
NetPeerTcpBinding np2p = new NetPeerTcpBinding();
np2p.Security.Mode = SecurityMode.None;
}
private void btnSendURL_MouseClick(object sender, EventArgs e)
{
ApplicationService url = new ApplicationService();
url.GetURL();
}
[ServiceContract]
public interface IApplicationService
{
[OperationContract]
string GetURL();
}
public class ApplicationService : IApplicationService
{
public string GetURL()
{
return Clipboard.GetText(TextDataFormat.Text);
}
}
private void btnSendURL_MouseClick(object sender, EventArgs e)
{
ApplicationService url = new ApplicationService();
string data = url.GetURL();
listBox1.Items.AddRange(addCopy.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}