我上了这个课:
public class MyRect : FrameworkElement
{
public Visual Visual { get; set; }
protected override int VisualChildrenCount => 1;
protected override Visual GetVisualChild(int index) => Visual;
protected override void OnRender(DrawingContext drawingContext)
{
var drawing = new DrawingVisual();
using (var dc = drawing.RenderOpen())
{
var brush = new SolidColorBrush(Colors.Green);
var pen = new Pen(new SolidColorBrush(Colors.Blue),1);
var rect = new Rect(new Size(Width,Height));
dc.DrawRectangle(brush,pen,rect);
}
Visual = drawing;
}
}
用于绘制矩形。单击按钮后,会将新的Rectangle
添加到名为ObservableCollection
的{{1}}:
RectCollection
并且RectCollection.Insert(0,new MyRect() {Width = 20,Height = rand.NextDouble() * 100 });
是RectCollection
的{{1}}:
ItemSource
它绘制矩形,但它们之间没有空格。我尝试像这样在ItemsControl
中设置边距:
<ItemsControl ItemsSource="{Binding RectCollection}" VerticalAlignment="Bottom" VerticalContentAlignment="Bottom">
<ItemsControl.ItemsPanel>
<itemspaneltemplate>
<StackPanel Orientation="Horizontal"/>
</itemspaneltemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
那是行不通的!另一个问题是DataTemplate
的矩形底部与基线未对齐。
编辑
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Width="35" Margin="5 0 5 0"/>
</DataTemplate>
</ItemsControl.ItemTemplate>