我想我正在尝试在WPF中做一些相对简单的事情,但不能为我的生活弄清楚如何;并且我认为我可能正处于过度复杂化的边缘。
如果我有一个3行3列的网格,并且我想加入两个单元格的角来创建对角线边框,那么最好的方法是什么?
如果控件调整大小(因此绑定到单元格的角落?),理想情况下,这些行应该重新调整大小。
基本上我想在这里托管的图表中创建红线:Example Pic http://imm.io/7A4L
答案 0 :(得分:25)
您可以使用带Stretch = Fill的路径。对于示例中的右上角单元格,您将使用:
<Path Grid.Row="2" Grid.Column="0" Stroke="Red" StrokeThickness="2" Stretch="Fill">
<Path.Data>
<LineGeometry StartPoint="0,0" EndPoint="1,1" />
</Path.Data>
</Path>
“Fill”拉伸使Path伸展以填充其父级,这给人的印象是LineGeometry的坐标是相对的(X = 0,Y = 0是左上角,X = 1,Y = 1是底部右)。
答案 1 :(得分:2)
我已经创建了一个样本来从后面的代码中绘制线条,这将为您提供更多控制权... 我创建了一个网格,其中包含每个单元格中的画布和画布上的负载我正在创建一个路径并将其添加到同一个画布...
正如@ Mathieu Garstecki的回答我们可以在xaml中实现这个crating路径...如果想在创建路径之前添加一些逻辑,你可以使用我的答案 的 XAML 强>
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Canvas Grid.Row="0" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="AliceBlue" Loaded="Canvas_Loaded"></Canvas>
<Canvas Grid.Row="1" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="AliceBlue" Loaded="Canvas_Loaded"></Canvas>
<Canvas Grid.Row="2" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="AliceBlue" Loaded="Canvas_Loaded"></Canvas>
<Canvas Grid.Row="0" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="AliceBlue" Loaded="Canvas_Loaded"></Canvas>
<Canvas Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="AliceBlue" Loaded="Canvas_Loaded"></Canvas>
<Canvas Grid.Row="2" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="AliceBlue" Loaded="Canvas_Loaded"></Canvas>
<Canvas Grid.Row="0" Grid.Column="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="AliceBlue" Loaded="Canvas_Loaded"></Canvas>
<Canvas Grid.Row="1" Grid.Column="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="AliceBlue" Loaded="Canvas_Loaded"></Canvas>
<Canvas Grid.Row="2" Grid.Column="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="AliceBlue" Loaded="Canvas_Loaded"></Canvas>
</Grid>
代码背后
private void Canvas_Loaded(object sender, RoutedEventArgs e)
{
var g = new StreamGeometry();
var context = g.Open();
context.BeginFigure(new Point(0, 0), true, true);
context.LineTo(new Point((sender as Canvas).ActualHeight, (sender as Canvas).ActualWidth), true, true);
context.Close();
System.Windows.Shapes.Path path = new System.Windows.Shapes.Path();
path.Data = g;
path.Stroke = new SolidColorBrush(Colors.Red);
path.StrokeThickness = 1.4;
(sender as Canvas).Children.Add(path);
}
<强>输出强>