0

我需要使用 C# WPF 绘制用户定义数量的网格。如果允许的最大网格数很大,我的代码可以工作,但会过长 - 有没有更简洁的方法?

以下代码显示了当前如何在 gridCanvas(一个 WPF 网格控件)上绘制 1 个网格 - 对于可能需要的每个附加网格,都会重复该网格。

private void DrawInvGrid(int[,] initialPosn)
{          
    PathFigure myPathFigure1 = new PathFigure();
    GeometryGroup myGeometryGroup1 = new GeometryGroup();
    LineSegment myLineSegment1 = new LineSegment();      
    PathSegmentCollection myPathSegmentCollection1 = new PathSegmentCollection();
    PathFigureCollection myPathFigureCollection1 = new PathFigureCollection();

    // repeat declarations for each grid

    int gridx = 5;
    int gridy = 5;
    int gridsize = 11;

    // create grid 1

    for (int z = 0; z < 5; z++)
    {
        int startpt_1x = (initialPosn[0, 0] - 5);
        int startpt_1y = (initialPosn[0, 1] - 5);
        for (int i = 0; i <= gridx; i++)
        {
            myPathFigure1 = new PathFigure();
            myPathSegmentCollection1 = new PathSegmentCollection();
            myPathFigure1.StartPoint = new System.Windows.Point(startpt_1x + 
                                                         (i * gridsize), startpt_1y);

            myLineSegment1 = new LineSegment();
            myLineSegment1.Point = new System.Windows.Point(startpt_1x + (i * gridsize),
                                                startpt_1y + gridy * gridsize);
            myPathSegmentCollection1.Add(myLineSegment1);
            myPathFigure1.Segments = myPathSegmentCollection1;
            myPathFigureCollection1.Add(myPathFigure1);

            xgridpos1.Add(startpt_1x + (i * gridsize));
         }

         for (int i = 0; i <= gridy; i++)
         {
             myPathFigure1 = new PathFigure();
             myPathSegmentCollection1 = new PathSegmentCollection();
             myPathFigure1.StartPoint = new System.Windows.Point(startpt_1x, startpt_1y +
                                                    (i * gridsize));
             myLineSegment1 = new LineSegment();
             myLineSegment1.Point = new System.Windows.Point(startpt_1x + gridx * 
                          ridsize, startpt_1y + (i * gridsize));
             myPathSegmentCollection1.Add(myLineSegment1);
             myPathFigure1.Segments = myPathSegmentCollection1;
             myPathFigureCollection1.Add(myPathFigure1);

             ygridpos1.Add(startpt_1y + (i * gridsize));
         }
    }  

    // repeat grid creation loop for each grid

    // display grid 1
    gridCanvas.Children.Clear();
    PathGeometry myPathGeometry1 = new PathGeometry();
    myPathGeometry1.Figures = myPathFigureCollection1;

    myPath1.Stroke = System.Windows.Media.Brushes.Green;
    myPath1.StrokeThickness = 1;
    myPath1.ToolTip = gridname;
    myPath1.Data = myPathGeometry1;

    gridCanvas.Children.Add(myPath1);

    // repeat display routine for each grid
}

在任何特定运行中,所有网格都是相同的 - 只有网格的位置(由 定义int[,] initialPosn)因网格而异。任何有关更有效替代方案的建议表示赞赏。

4

1 回答 1

1

将重复代码提取到一个方法中,该方法仅将那些变化的值(在您的情况下为位置)作为参数。

于 2013-07-02T11:24:37.137 回答