原文地址:http://www.cnblogs.com/limo/archive/2010/12/14/1905172.html

1,新建一个Silverlight Application,里面会有一个MainPage.xaml文件 和对应的MainPage.xaml.cs文件,随便在xaml中写点什么

例如我写了点这个,下面是MainPage.xaml全部代码

01 <UserControl x:Class="UserControlDemo.MainPage"
06     mc:Ignorable="d"
07     d:DesignHeight="300" d:DesignWidth="400">
08   
09     <Grid x:Name="LayoutRoot" Background="White">
10         <StackPanel Height="86" HorizontalAlignment="Left" Margin="94,90,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="200">
11             <TextBlock Height="36" Name="myTextBlock" Text="默认值" />
12             <Button Content="Button" Height="23" Name="myBtn" Width="75" />
13         </StackPanel>
14     </Grid>
15 </UserControl>

2,在项目下 再添加一个Silverlight Page 页面 或者 Silverlight User Control 都行 ,我添加了一个Page.并且导入了一个命名空间xmlns:myUserControl="clr-namespace:UserControlDemo", 其中myUserControl是个名字可以随便写. 这样就能在这个页面中引用UserControlDemo这个命名空间中的类了.所以我在Page这页面的Grid中可以用到MainPage这个类了.

下面是Page.xaml的代码

01 <navigation:Page x:Class="UserControlDemo.Page1" 
02            xmlns:myUserControl="clr-namespace:UserControlDemo"
04            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
05            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
07            mc:Ignorable="d"
08            xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
09            d:DesignWidth="640" d:DesignHeight="480"
10            Title="Page1 Page">
11     <Grid x:Name="LayoutRoot">
12         <myUserControl:MainPage x:Name="demoUserControl" Msg="UserControlDemo"></myUserControl:MainPage>
13     </Grid>
14 </navigation:Page>

这时会发现 我在用MainPage 这个类的时候 有一个Msg 属性,这个属性不是silverlight 类中的,那很显然 就是自己给MainPage 加的属性.

代码如下

01 namespace UserControlDemo
02 {
03     public partial class MainPage : UserControl
04     {
05         public String Msg 
06         {
07             set 
08             {
09                 myTextBlock.Text = value;
10             }
11             get
12             {
13                 return myTextBlock.Text;   
14             }
15         }
16         public MainPage()
17         {
18             InitializeComponent();
19         }
20     }
21 }

的确是咱自己加的属性,只不过这个属性的值会在MainPage.xaml的Textblock中显示.

差点忘了,最后把VS自动生成的App.xaml.cs里面的启动函数修改一下,启动页改成Page.

1 private void Application_Startup(object sender, StartupEventArgs e)
2         {
3             //this.RootVisual = new MainPage();
4             this.RootVisual = new Page1();
5         }

不知不觉 你就会发现 其实 这就是自定义控件的开始.

相关文章: