概述 Silverlight 2 Beta 1版本发布了无论从Runtime还是Tools都给我们带来了很多惊喜如支持框架语言Visual Basic, Visual C#, IronRuby, Ironpython对JSON、Web Service、WCF以及Sockets支持等系列新特性步步学Silverlight 2系列文章带您快速进入Silverlight 2开发
本文为系列文章第10篇主要介绍Silverlight 2中用户Control控件使用
创建用户Control控件 在Silverlight 2中我们可以根据开发自定义Control控件或者创建用户Control控件以达到Control控件重用目添加个新用户Control控件:
编写用户Control控件实现代码:
<Grid x:Name="LayoutRoot" Background="White">
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Opacity="0.7" Fill="#FF8A8A8A"/>
<Border CornerRadius="15" Width="400" Height="150" Background="LightPink" Opacity="0.9">
<StackPanel Orientation="Horizontal" Height="50">
<Image Source="info.png" Margin="10 0 0 0"></Image>
<Button Background="Red" Width="120" Height="40"
Content="OK" Margin="10 0 0 0" FontSize="18"/>
<Button Background="Red" Width="120" Height="40"
Content="Cancel" Margin="50 0 0 0" FontSize="18"/>
</StackPanel>
</Border>
</Grid>
在需要使用该用户Control控件页面XAML中注册命名空间:使用用户Control控件:
<Grid x:Name="LayoutRoot" Background="#46461F">
<uc:ConfirmBox x:Name="mybox"></uc:ConfirmBox>
</Grid>
整个过程就这么简单运行后效果如下:为用户Control控件添加属性 简单修改下上面举例中XAML文件添加个文本块Control控件用它来显示文字提示信息
<Grid x:Name="LayoutRoot" Background="White">
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Opacity="0.7" Fill="#FF8A8A8A"/>
<Border CornerRadius="15" Width="400" Height="150" Background="LightPink" Opacity="0.9">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60"></RowDefinition>
<RowDefinition Height="90"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock x:Name="message" FontSize="18" Foreground="White"
HorizontalAlignment="Left" VerticalAlignment="Center"
Margin="50 20 0 0"/>
<StackPanel Orientation="Horizontal" Height="50" Grid.Row="1">
<Image Source="info.png" Margin="10 0 0 0"></Image>
<Button Background="Red" Width="120" Height="40"
Content="OK" Margin="10 0 0 0" FontSize="18"/>
<Button Background="Red" Width="120" Height="40"
Content="Cancel" Margin="50 0 0 0" FontSize="18"/>
</StackPanel>
</Grid>
</Border>
</Grid>
定义属性:public partial ConfirmBox : UserControl
{
public ConfirmBox
{
InitializeComponent;
}
public String Message
{
get { this.message.Text; }
{ this.message.Text = value; }
}
}
在页面使用用户Control控件属性XAML编辑器能够识别出属性并提示:为ConfirmBoxControl控件Message属性赋值:
<Grid x:Name="LayoutRoot" Background="#46461F">
<uc:ConfirmBox x:Name="mybox" Message="使用用户Control控件成功"></uc:ConfirmBox>
</Grid>
运行后效果如下所示:动态添加用户Control控件 用户Control控件可以动态添加到页面中修改下Page.xaml中XAML代码放入个Canvas作为用户Control控件容器
<Grid x:Name="LayoutRoot" Background="#46461F">
<Canvas x:Name="ContainerCanvas">
</Canvas>
</Grid>
编写添加用户Control控件代码:private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
{
ConfirmBox confirmbox = ConfirmBox;
confirmbox.Message = "动态添加用户Control控件成功!";
ContainerCanvas.Children.Add(confirmbox);
}
运行后效果如下所示当然我们也可以控制用户Control控件显示位置等结束语 本文简单介绍了在Silverlight 2中使用用户Control控件包括创建用户Control控件、添加属性、动态添加用户Control控件等内容你可以下载本文举例代码
最新评论