2013-06-28 35 views

回答

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; 
+0

感謝託尼奧,但這樣一來,我只能在template..what添加一個控制,如果我的模板必須得到多行控制,即文本框,單選按鈕,列表框等垂直每行。每個行應該能夠得到一個標籤和控制裏面它當頁面上應用模板 – Gobind

+0

如果我明白你想使用['ItemsControl '](http://msdn.microsoft.com/library/system.windows.controls.itemscontrol(v = VS.95)的.aspx)。 – Tonio

+0

是的....但即使我使用ItemsControl創建模板,仍然只能通過一個控件(例如文本框,複選框等)...我怎麼能通過堆棧中的多個控件,即每個行有一個控制 – Gobind

相關問題