您的位置:首页 > 理论基础 > 计算机网络

初识UserControl _转http://www.cnblogs.com/limo/archive/2010/12/14/1905172.html

2011-01-05 15:11 281 查看
原文地址:http://www.cnblogs.com/limo/archive/2010/12/14/1905172.html

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

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

showsourceviewsource

print?

01
<UserControlx:Class=
"UserControlDemo.MainPage"
02
xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation"
03
xmlns:x=
"http://schemas.microsoft.com/winfx/2006/xaml"
04
xmlns:d=
"http://schemas.microsoft.com/expression/blend/2008"
05
xmlns:mc=
"http://schemas.openxmlformats.org/markup-compatibility/2006"
06
mc:Ignorable=
"d"
07
d:DesignHeight=
"300"
d:DesignWidth=
"400"
>
08
09
<Gridx:Name=
"LayoutRoot"
Background=
"White"
>
10
<StackPanelHeight=
"86"
HorizontalAlignment=
"Left"
Margin=
"94,90,0,0"
Name=
"stackPanel1"
VerticalAlignment=
"Top"
Width=
"200"
>
11
<TextBlockHeight=
"36"
Name=
"myTextBlock"
Text=
"默认值"
/>
12
<ButtonContent=
"Button"
Height=
"23"
Name=
"myBtn"
Width=
"75"
/>
13
</StackPanel>
14
</Grid>
15
</UserControl>
2,在项目下再添加一个SilverlightPage页面或者SilverlightUserControl都行,我添加了一个Page.并且导入了一个命名空间xmlns:myUserControl="clr-namespace:UserControlDemo",其中myUserControl是个名字可以随便写.这样就能在这个页面中引用UserControlDemo这个命名空间中的类了.所以我在Page这页面的Grid中可以用到MainPage这个类了.

下面是Page.xaml的代码

showsourceviewsource

print?

01
<navigation:Pagex:Class=
"UserControlDemo.Page1"
02
xmlns:myUserControl=
"clr-namespace:UserControlDemo"
03
xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation"
04
xmlns:x=
"http://schemas.microsoft.com/winfx/2006/xaml"
05
xmlns:d=
"http://schemas.microsoft.com/expression/blend/2008"
06
xmlns:mc=
"http://schemas.openxmlformats.org/markup-compatibility/2006"
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=
"Page1Page"
>
11
<Gridx:Name=
"LayoutRoot"
>
12
<myUserControl:MainPagex:Name=
"demoUserControl"
Msg=
"UserControlDemo"
></myUserControl:MainPage>
13
</Grid>
14
</navigation:Page>
这时会发现我在用MainPage这个类的时候有一个Msg属性,这个属性不是silverlight类中的,那很显然就是自己给MainPage加的属性.

代码如下

showsourceviewsource

print?

01
namespace
UserControlDemo
02
{
03
public
partial
class
MainPage:UserControl
04
{
05
public
StringMsg
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.

showsourceviewsource

print?

1
private
void
Application_Startup(
object
sender,StartupEventArgse)
2
{
3
//this.RootVisual=newMainPage();
4
this
.RootVisual=
new
Page1();
5
}
不知不觉你就会发现其实这就是自定义控件的开始.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐