Last year I wrote an article about how to pass event information between multiple Silverlight applications on the same page.
The trick was to pass on HTML page elements, which, of course, also supported the delivery of information to other Third-party ActiveX controls. But because of the introduction of JS code, so that developers feel a bit awkward. It is certain that this kind of message passing is more easily accepted in CS code.
Fortunately, the SILVERLIGHT3 Beta provides two important classes that start with "Localmessage" and are located under the "System.Windows.Messaging" namespace:
LocalMessageSender :消息发送器类
LocalMessageReceiver:消息接收器类
As the name suggests, they are the so-called "sender" and "receiver" of the message.
And using them is simple, first we have to create a SILVERLIGHT3 beta project, called: Localmessage.
The following XAML code is then copied to the MainPage.xaml file:
<UserControl x:Class="LocalMessage.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="200">
<StackPanel x:Name="LayoutRoot" Background="AliceBlue">
<TextBox
Margin="10"
FontSize="24"
x:Name="txtMessage" />
<Button
Content=" 发 送 "
HorizontalAlignment="Right"
Margin="10"
Click="OnSendMessage" />
<TextBlock TextWrapping="Wrap"
Foreground="Blue"
FontSize="12"
x:Name="txtResponse"
HorizontalAlignment="Center" />
</StackPanel>
</UserControl>
The following is the corresponding CS code:
void OnSendMessage(object sender, RoutedEventArgs args)
{
LocalMessageSender msgSender = new LocalMessageSender("MessageContact", "localhost");
EventHandler<SendCompletedEventArgs> handler = null;
handler = (s, e) =>
{
Dispatcher.BeginInvoke(() =>
{
msgSender.SendCompleted -= handler;
if (e.Error != null)
{
txtResponse.Text = String.Format("错误 [{0}]", e.Error.Message);
}
else
{
txtResponse.Text = String.Format("响应 [{0}]", e.Response == null ? "None" : e.Response);
}
});
};
msgSender.SendCompleted += handler;
msgSender.SendAsync(txtMessage.Text);
}