14.1.1 创建自定义控件(1)(图)

This item was filled under [ 新闻News ]

  14.1.1 创建自定义控件(1) 

  自定义控件定义了一系列部件和状态模型,这些部件和状态组成了自定义控件的界面和行为。

  创建自定义控件的过程包括创建自定义控件界面、创建交互行为和定义控件契约。这里以创建一个NumericUpDown的用户控件为例,介绍如何创建一个自定义控件。

  NumericUpDown的界面元素包括:两个RepeatButton控件和一个TextBox控件。TextBox控件用来显示当前的数值,其中一个RepeatButton控件用来使数值上升,另一个用来使数值下降。如图14-1所示。

  图14-1 NumericUp

  Down控件的界面元素

  具体操作步骤如下。

  (1)新建Silverlight工程,命名为NumbericUpDownSample。创建一个类,命名为NumbericUpDown。将其继承关系设为继承自Control。代码如下:

  public class NumbericUpDown : Control

  (2)创建文件generic.xaml,并将其放在Themes文件夹下。

  generic.xaml文件只用来放置项目中用到的资源,如项目中所需要用到的模板和样式等。

  可以用创建UserControl的方式创建一个generic.xaml的UserControl,然后将generic.cs文件删除,如图14-2所示。

 

图14-2 在工程中添加generic.xaml文件

  打开generic.xaml文件,将代码改为: 

  <ResourceDictionaryxmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”></ResourceDictionary

  (3)在generic.xaml文件中添加默认的样式。

  在generic.xaml文件中创建的样式无法用Blend打开,所以这里要用到的一个技巧是:先在Page.xaml中创建好默认的模板样式,然后将XAML代码复制到generi.xaml中。默认的模板样式如例程14-1所示。

  例程14-1 使用默认样式

  <ResourceDictionaryxmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”xmlns:local=”clr-namespace:NumbericUpDownSample”xmlns:vsm=”clr-namespace:System.Windows;assembly=System.Windows”>

  <Style TargetType=”local:NumbericUpDown”>

  <Setter Property=”Template”>

  <ControlTemplate TargetType=”local:NumbericUpDown”>

  <Grid >

  <Grid.RowDefinitions>

  <RowDefinition/>

  <RowDefinition/>

  </Grid.RowDefinitions>

  <Grid.ColumnDefinitions>

  <ColumnDefinition/>

  <ColumnDefinition/>

  </Grid.ColumnDefinitions>

  <TextBox x:Name=”TextBox” FontSize=”12″

  Grid.RowSpan=”2″ border=”1″ Height=”Auto”

  Margin=”5,0,5,0″

  HorizontalAlignment=”Stretch”

  VerticalAlignment=”Center”/>

  <RepeatButton x:Name=”UpButton” Content=”Up”

  Margin=”2,5,5,0″

  Grid.Column=”1″ Grid.Row=”0″/>

  <RepeatButton x:Name=”DownButton” Content=”Down”

  Margin=”2,0,5,5″

  Grid.Column=”1″ Grid.Row=”1″/>

  </Grid>

  </ControlTemplate>

  </Setter>

  </Style>

  </ResourceDictionary>

【来源:51cto】 (责任编辑:和讯网站)

喜欢这篇文章的人还喜欢。。。

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Comment

Anti-spam text: (Required) *
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text. Click to hear an audio file of the anti-spam word