ItemsControl中的间距和对齐矩形

问题描述 投票:0回答:1

我上这堂课:

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添加到名为ObservableCollectionRectCollection

RectCollection.Insert(0, new MyRect() {Width = 20, Height = rand.NextDouble() * 100 }); 

并且RectCollectionItemSourceItemsControl

<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"的矩形底部未与基线对齐。

c# wpf itemscontrol
1个回答
0
投票

Here我找到了Rohit Vats

提供的解决方案
<ItemsControl.ItemContainerStyle>
    <Style>
        <Setter Property="FrameworkElement.Margin" Value="2.5"/>
        <Setter Property="FrameworkElement.VerticalAlignment" Value="Bottom"/>
    </Style>
</ItemsControl.ItemContainerStyle>

它实际上完成了我想要的!

© www.soinside.com 2019 - 2024. All rights reserved.