2012-01-10 67 views
0

我试图创建一个通用的观点,我希望它包含一个列表框与一个DataTemplate创建的ListBox的DataTemplate

我要创建它要么通过XAML使用纯C#代码,或者如果可能的负载呢?如果我可以创建一个模板,我可以在c#中作为各种资源。

我已经取得直到现在

 private static ListBox CreateDayListBox() 
    { 
     var listBox = new ListBox(); 
     var dataTemplate = new DataTemplate(); 

     var grid = new Grid(); 
     var columnDefinition1 = new ColumnDefinition {Width = GridLength.Auto}; 
     var columnDefinition2 = new ColumnDefinition(); 

     grid.ColumnDefinitions.Add(columnDefinition1); 
     grid.ColumnDefinitions.Add(columnDefinition2); 

     var rectangleItemBought = new Rectangle {Width = 50, Height = 50}; 
     rectangleItemBought.SetBinding(Rectangle.FillProperty, new Binding("Bought")); 
     grid.Children.Add(rectangleItemBought); 

     var textBlockItemName = new TextBlock(); 
     textBlockItemName.SetBinding(TextBlock.TextProperty, new Binding("Name")); 
     var textBlockItemQuantity = new TextBlock(); 
     textBlockItemQuantity.SetBinding(TextBlock.TextProperty, new Binding("Quantity")); 
     var textBlockItemQuantityType = new TextBlock(); 
     textBlockItemQuantityType.SetBinding(TextBlock.TextProperty, new Binding("QuantityType")); 

     var stackpanel = new StackPanel(); 
     Grid.SetColumn(stackpanel, 1); 
     stackpanel.Children.Add(textBlockItemName); 
     stackpanel.Children.Add(textBlockItemQuantity); 
     stackpanel.Children.Add(textBlockItemQuantityType); 
     grid.Children.Add(stackpanel); 

     return listBox; 
    } 

所以我想在列表框DataTemplate中包含1个矩形,1个StackPanel中有3个文本框里面

回答

1

你可以写在XAML模板然后加载它你的代码。

阅读this

而且,我敢肯定,你可以通过代码创建的DataTemplate你创建的控制以同样的方式,看看这段代码(credit):

DataTemplate template = new DataTemplate(); 
FrameworkElementFactory factory = 
    new FrameworkElementFactory(typeof(StackPanel)); 
template.VisualTree = factory; 
FrameworkElementFactory childFactory = 
    new FrameworkElementFactory(typeof(Image)); 
childFactory.SetBinding(Image.SourceProperty, new Binding("Machine.Thumbnail")); 
childFactory.SetValue(Image.WidthProperty, 170.0);  
childFactory.SetValue(Image.HeightProperty, 170.0); 
factory.AppendChild(childFactory); 
childFactory = new FrameworkElementFactory(typeof(Label)); 
childFactory.SetBinding(Label.ContentProperty, 
    new Binding("Machine.Descriiption")); 
childFactory.SetValue(Label.WidthProperty, 170.0); 
childFactory.SetValue(Label.HorizontalAlignmentProperty, 
    HorizontalAlignment.Center); 
factory.AppendChild(childFactory); 
+0

应该工作,但可以看到这个方法不工作在WP7上(我没有提及,不知道这很重要) – Mech0z 2012-01-10 12:15:13

+0

哪种方法?上面的代码是pseudu ...我相信WP7(从来没有用过它)提供XAML解析。 – Shimmy 2012-01-10 13:51:42