Skip to main content
 首页 » 编程设计

c#之带网格线的 Winrt 自定义网格控件

2024年02月20日13bluestorm

我想做一个自定义网格控件,因为默认不支持显示网格线。我为此找到了一个 wpf 解决方案,但 winrt 缺少 wpf 支持的一些功能。 wpf 解决方案中的代码是这样的:

     protected override void OnRender(DrawingContext dc) 
    { 
        if (ShowCustomGridLines) 
        { 
            foreach (var rowDefinition in RowDefinitions) 
            { 
                dc.DrawLine(new Pen(GridLineBrush, GridLineThickness), new Point(0, rowDefinition.Offset), new Point(ActualWidth, rowDefinition.Offset)); 
            } 
 
            foreach (var columnDefinition in ColumnDefinitions) 
            { 
                dc.DrawLine(new Pen(GridLineBrush, GridLineThickness), new Point(columnDefinition.Offset, 0), new Point(columnDefinition.Offset, ActualHeight)); 
            } 
            dc.DrawRectangle(Brushes.Transparent, new Pen(GridLineBrush, GridLineThickness), new Rect(0, 0, ActualWidth, ActualHeight)); 
        } 
        base.OnRender(dc); 
    } 

但是我不能重写onrender方法,winrt中也没有drawingcontext。那么如何将网格线绘制到我的网格中呢? 感谢您的帮助!

请您参考如下方法:

如果您不想在每个元素周围放置边框,我所做的基本上就是您所做的,但在 xaml 中基本上只是绘制它们,例如;

<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left"> 
    <Grid> 
        <Grid.RowDefinitions> 
            <RowDefinition Height="20"/>     
            <RowDefinition Height="20"/> 
            <RowDefinition Height="20"/> 
            <RowDefinition Height="20"/> 
            <RowDefinition Height="20"/>         
        </Grid.RowDefinitions> 
        <Grid.ColumnDefinitions> 
            <ColumnDefinition Width="20"/> 
            <ColumnDefinition Width="20"/> 
            <ColumnDefinition Width="20"/> 
            <ColumnDefinition Width="20"/> 
            <ColumnDefinition Width="20"/> 
        </Grid.ColumnDefinitions> 
        <!-- Horizontal Lines --> 
        <Rectangle Grid.ColumnSpan="5" Height="1" VerticalAlignment="Bottom" Fill="Black"/> 
        <Rectangle Grid.Row="1" Grid.ColumnSpan="5" Height="1" VerticalAlignment="Bottom" Fill="Black"/> 
        <Rectangle Grid.Row="2" Grid.ColumnSpan="5" Height="1" VerticalAlignment="Bottom" Fill="Black"/> 
        <Rectangle Grid.Row="3" Grid.ColumnSpan="5" Height="1" VerticalAlignment="Bottom" Fill="Black"/> 
        <Rectangle Grid.Row="4" Grid.ColumnSpan="5" Height="1" VerticalAlignment="Bottom" Fill="Black"/> 
        <!-- Vertical Lines --> 
        <Rectangle Grid.RowSpan="5" Width="1" HorizontalAlignment="Right" Fill="Black"/> 
        <Rectangle Grid.Column="1" Grid.RowSpan="5" Width="1" HorizontalAlignment="Right" Fill="Black"/> 
        <Rectangle Grid.Column="2" Grid.RowSpan="5" Width="1" HorizontalAlignment="Right" Fill="Black"/> 
        <Rectangle Grid.Column="3" Grid.RowSpan="5" Width="1" HorizontalAlignment="Right" Fill="Black"/> 
    </Grid> 
</Border> 

通过这种方式,您可以按照自己喜欢的方式排列单元格,并且可以减少必须将所有内容嵌套在边框中的情况。希望能帮助到你。干杯!