在C#中创建ListBox DataTemplate



我正在尝试创建一个通用视图,我希望它包含一个带有数据模板的ListBox

我想使用纯C#代码创建它,或者如果可能的话,通过xaml加载它?如果我能创建一个模板,我就可以把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;
    }

因此,我希望列表框数据模板包含1个矩形,1个堆叠面板,内有3个文本框

您可以在XAML中编写模板,然后将其加载到代码中。

读这个。

此外,我很确定你可以像创建控件一样通过代码创建DataTemplate,看看这个代码(信用):

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);

最新更新