在ItemsControl中间距和对齐矩形

我上了这个课:

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> 
cggsj 回答:在ItemsControl中间距和对齐矩形

这里是一个简单条形图的示例,仅在ItemsControl的ItemTemplate中使用一些基本元素:

<ItemsControl ItemsSource="{Binding}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid Width="20" Height="100" Margin="2">
                <Rectangle VerticalAlignment="Bottom"
                           Height="{Binding}"
                           Fill="LightGray"/>
                <TextBlock Text="{Binding StringFormat={}{0:N2}}">
                    <TextBlock.LayoutTransform>
                        <RotateTransform Angle="-90"/>
                    </TextBlock.LayoutTransform>
                </TextBlock>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

其DataContext设置为双精度值的集合,例如喜欢:

Random r = new Random();

DataContext = Enumerable.Range(0,20).Select(i => r.NextDouble() * 100);
本文链接:https://www.f2er.com/2989357.html

大家都在问