自定义SilverLight容器控件

时间:2012-07-13 06:19:01

标签: silverlight xaml user-controls

我想创建一个新的Silverlight容器控件,控件应该包含两个按钮,默认情况下是一个Save和一个Cancel按钮。当用户在主页面上使用此控件时,他应该能够向该控件添加新控件,如文本框,组合等。此外,用户可以使用btn_SaveClick和btn_CancelClick等默认按钮的事件代码进行编码主页背后。是否可以创建这样的控件?
PS:我目前在VS2010上使用SilverLight5。

1 个答案:

答案 0 :(得分:0)

这绝对是可能的。首先,您需要一个派生自ContentControl的类:

public class MyControl : ContentControl ...

然后在XAML资源文件中需要与此类似的代码:

<!-- MyControl -->
<Style TargetType="me:MyControl">
    <Setter Property="Foreground" Value="Black" />
    <Setter Property="BorderBrush" Value="Transparent" />
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="HorizontalAlignment" Value="Stretch" />
    <Setter Property="VerticalAlignment" Value="Stretch" />
    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    <Setter Property="VerticalContentAlignment" Value="Stretch" />
    <Setter Property="BorderMargin" Value="4,4,4,0" />
    <Setter Property="FooterMargin" Value="4,0,4,4" />

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="me:MyControl">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>

                    <!-- Content -->
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                                            VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />

                    <!-- Footer Buttons -->
                    <Grid x:Name="grdFooter" Grid.Row="1" Background="{StaticResource Footer_Bkg}" Margin="{TemplateBinding FooterMargin}">
                        <!--Buttons here-->
                    </Grid>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

最后要在页面中使用它,你只需要这样的东西:

<me:MyControl x:Name="MainPage">
    <Grid x:Name="LayoutRoot">
        <!--Cool stuff here-->
    </Grid>
</me:MyControl>