我有一个在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;
}
}
Run Code Online (Sandbox Code Playgroud)
首先,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);
} );
}
}
Run Code Online (Sandbox Code Playgroud)
这基本上是@Simon Fox提出的解决方案,即使用委托.可以这么说,这可能只会给骨头带来一些肉体.
使用代表。在表单的代码隐藏中创建一个委托,该委托引用写入文本框的方法并将其传递给服务,然后服务可以在想要打印消息时调用该委托。
您在尝试更新文本框时会遇到问题,因为将在与创建文本框的线程不同的线程上调用委托。在 WPF 世界中,您可以使用 Dispatcher.BeginInvoke 来解决此问题,但不确定 WinForms 的等效项是什么。
归档时间: |
|
查看次数: |
2746 次 |
最近记录: |