【问题标题】:Custom SilverLight Container Control自定义 SilverLight 容器控件
【发布时间】:2012-07-13 06:19:00
【问题描述】:

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

【问题讨论】:

    标签: silverlight xaml user-controls


    【解决方案1】:

    这绝对是可能的。首先你需要一个从 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 2011-06-15
      • 2011-03-17
      • 2011-09-28
      • 2012-07-15
      相关资源
      最近更新 更多