1)用户控件SilverlightControl1.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightApplication20
{
public partial class SilverlightControl1 : UserControl
{
/// <summary>
/// 定义委托
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void MyDelegate(object sender, EventArgs e);
/// <summary>
/// 定义事件
/// </summary>
public event MyDelegate myEvent;
private Button TestButton = null;
public SilverlightControl1()
{
InitializeComponent();
TestButton = new Button();
TestButton.Width = 200;
TestButton.Height = 24;
TestButton.Content = "Test";
TestButton.Click+=new RoutedEventHandler(TestButton_Click);
LayoutRoot.Children.Add(TestButton);
}
private void TestButton_Click(object sender, RoutedEventArgs e)
{
//将自定义事件绑定到控件事件上
if (myEvent != null)
{
myEvent(sender, e);
}
}
}
}
2)调用页面Home.xaml.cs(温馨提示调用用户控件一定要是Silverlight Page)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SilverlightApplication20
{
public partial class Home : Page
{
private StackPanel TestStackPanel = null;
private SilverlightControl1 silverlightControl1 = null;
private TextBlock TestBlock = null;
public Home()
{
InitializeComponent();
//StackPanel
TestStackPanel = new StackPanel();
LayoutRoot.Children.Add(TestStackPanel);
//字定义控件
silverlightControl1 = new SilverlightControl1();
silverlightControl1.myEvent += new SilverlightControl1.MyDelegate(silverlightControl1_myEvent);
TestStackPanel.Children.Add(silverlightControl1);
//TextBlock
TestBlock = new TextBlock();
TestBlock.Text = "Test";
TestStackPanel.Children.Add(TestBlock);
}
// Executes when the user navigates to this page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
void silverlightControl1_myEvent(object sender, EventArgs e)
{
TestBlock.Text = "Hello World!";
}
}
}
本文介绍了一个自定义的Silverlight用户控件,并演示了如何定义和触发自定义事件,以及如何在宿主页面中捕获这些事件并作出响应。
96

被折叠的 条评论
为什么被折叠?



