我有一个托管在 Windows 窗体内的 WCF 服务。
如何从我的服务中的方法访问表单的控件?
例如我有
public interface IService {
[ServiceContract]
string PrintMessage(string message);
}
public class Service: IService
{
public string PrintMessage(string message)
{
//How do I access the forms controls from here?
FormTextBox.Text = message;
}
}
首先,ServiceContract 属性应该位于接口上,而不是 PrintMessage() 方法上。
使用示例的更正版本,您可以这样做。
[ServiceContract]
public interface IService
{
[OperationContract]
string PrintMessage(string message);
}
public class Service : IService
{
public string PrintMessage(string message)
{
// Invoke the delegate here.
try {
UpdateTextDelegate handler = TextUpdater;
if (handler != null)
{
handler(this, new UpdateTextEventArgs(message));
}
} catch {
}
}
public static UpdateTextDelegate TextUpdater { get; set; }
}
public delegate void UpdateTextDelegate(object sender, UpdateTextEventArgs e);
public class UpdateTextEventArgs
{
public string Text { get; set; }
public UpdateTextEventArgs(string text)
{
Text = text;
}
}
public class MainForm : Form
{
public MainForm()
{
InitializeComponent();
// Update the delegate of your service here.
Service.TextUpdater = ShowMessageBox;
// Create your WCF service here
ServiceHost myService = new ServiceHost(typeof(IService), uri);
}
// The ShowMessageBox() method has to match the signature of
// the UpdateTextDelegate delegate.
public void ShowMessageBox(object sender, UpdateTextEventArgs e)
{
// Use Invoke() to make sure the UI interaction happens
// on the UI thread...just in case this delegate is
// invoked on another thread.
Invoke((MethodInvoker) delegate {
MessageBox.Show(e.Text);
} );
}
}
这本质上是 @Simon Fox 建议的解决方案,即使用委托。可以这么说,这希望只是在骨头上增添一些肉。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)