【发布时间】:2019-12-03 00:30:46
【问题描述】:
我有这门课:
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 将添加到名为RectCollection 的ObservableCollection:
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" 没有将矩形底部与基线对齐。
编辑
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 (drawingContext = drawing.RenderOpen())
{
var grid = new Grid();
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0, GridUnitType.Star) });
grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
var text = new TextBlock()
{
Text = Height.ToString("N2"),
Foreground = new SolidColorBrush(Colors.Black),
LayoutTransform = new RotateTransform(-90),
VerticalAlignment = VerticalAlignment.Top,
Margin = new Thickness(0, 0, 0, 5)
};
var border = new Border()
{
Width = Width,
Height = Height,
Background = new SolidColorBrush(Colors.Green),
CornerRadius = new CornerRadius(5, 5, 0, 0)
};
grid.Children.Add(text);
grid.Children.Add(border);
Grid.SetRow(border, 1);
grid.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
drawingContext.DrawRectangle(new VisualBrush(grid), null, new Rect(grid.DesiredSize));
}
Visual = drawing;
}
}
【问题讨论】:
-
这看起来很奇怪。在 ItemTemplate 和 MyRect 项目类中使用 Rectangle 元素,如下所示:stackoverflow.com/a/22325266/1136211。不要在视图模型中使用 UI 元素(如 MyRect)。
-
@Clemens,它实际上有一个
TextBlock和一个Border,如编辑部分所示。 -
那应该仍然是一个 UserControl,在 ItemTemplate 中实例化。你现在所拥有的效率非常低。视图模型中不应有 UI 元素。
-
@Clemens,你能否举一个简单的例子,
UserControl。它实际上是一个简单的条形图,顶部有值。 -
UserControl 是一个拥有自己的 XAML 的控件,您可以在其中定义其视觉外观。网上有很多例子。
标签: c# wpf itemscontrol