我上这堂课:
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
的RectCollection
:
RectCollection.Insert(0, new MyRect() {Width = 20, Height = rand.NextDouble() * 100 });
并且RectCollection
是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>
这不起作用!另一个问题是VerticalContentAlignment="Bottom"
的矩形底部未与基线对齐。
Here我找到了Rohit Vats:
提供的解决方案<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="FrameworkElement.Margin" Value="2.5"/>
<Setter Property="FrameworkElement.VerticalAlignment" Value="Bottom"/>
</Style>
</ItemsControl.ItemContainerStyle>
它实际上完成了我想要的!