我们如何创建Silverlight UserControl作为ContainerControl

时间:2013-06-28 07:25:37

标签: silverlight

我需要在Silverlight中创建UserControl as ContainterControl(或模板),以便我可以在其他Silverlight页面中使用它来添加控件....

任何答案都会很明显....感谢GK Prajapati

1 个答案:

答案 0 :(得分:0)

您要创建的内容是Silverlight Templated Control(扩展ContentControl)。

Sample on MSDN / Other sample

快速入门:

C#MyControl.cs

public class MyControl: ContentControl
{
    public MyControl()
        : base()
    {
        this.DefaultStyleKey = typeof(MyControl);
    }
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    }
}

XAML MyControl.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:MyControlNsp="clr-namespace:My.Control.NameSpace">
    <Style TargetType="UserToolkit:WarningBar">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="MyControlNsp:MyControl">
                    <Border>
                            <ContentControl
                                x:Name="content"
                                Content="{TemplateBinding Content}"
                                ContentTemplate="{TemplateBinding ContentTemplate}"
                                HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                                VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

编辑:
如果有不同的控件,您可以将ItemsControl与集合一起使用:

var myControl = new ItemsControl();
myControl.Items.Add(new TextBlock { Text = "My text block" });
myControl.Items.Add(new CheckBox { Content = "My check box" });
// Or with a collection of items
ObservableCollection<object> controls = new ObservableCollection<object>();
controls.Add(new TextBlock { Text = "My text block" });
controls.Add(new CheckBox { Content = "My check box" });
var myControl2 = new ItemsControl();
myControl2.ItemsSource = controls;