开发者

Draw grid with clickable rectangles

I need to draw a grid on my screen and with every click of the user draw an image on that specific area.

I don't know how to draw that grid. The squares will have fixed sizes (32x32 pixels) but their number will be variable. I could have a NxN cells grid. Also, this grid needs to be in a scrollpane as its s开发者_运维百科ize is variable. Does anyone know how to draw that grid and get the square clicked?

I'm using WPF.

Thanks.


Use ScrollViewer to enable scrolling capability

<ScrollViewer x:Name="layoutRoot" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"/>

then generate a Grid object:

private Grid GenerateGrid(int rows, int columns, int cellWidth, int cellHeight)
{
    Grid grid = new Grid();
    grid.Width = columns * cellWidth;
    grid.Height = rows * cellHeight;

    for (int i = 0; i < rows; i++)
    {
        grid.RowDefinitions.Add(new RowDefinition());
    }

    for (int i = 0; i < columns; i++)
    {
        grid.ColumnDefinitions.Add(new ColumnDefinition());
    }

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            var cell = new Border();
            cell.MouseDown += Cell_MouseDown;
            Grid.SetRow(cell, i);
            Grid.SetColumn(cell, j);
            cell.Background = Brushes.Transparent;

               cell.BorderBrush = Brushes.Gray;
               cell.BorderThickness = new Thickness(1);
            grid.Children.Add(cell);
        }
    }

    return grid;
}

private void Cell_MouseDown(object sender, MouseButtonEventArgs e)
{
    var cell = sender as Border; //You can use this object
}


In most cases where I need to know about mouse clicks, I tend to subclass Button. I find managing the base events for mouse handling to be somewhat annoying, but doing that would also work, and would be lighter weight if that matters to you. Either way, if you make a custom or user control, you should be able to have everything you need. You can override the OnClick (if you sub-class Button) or all four of OnPreviewMouseLeftButtonDown, OnPreviewMouseLeftButtonUp, OnMouseEnter, and OnMouseLeave if you'd rather manage it yourself. Capturing only mouse-up is not sufficient because you need to know if the mouse went down in your control as well. I recommend you observe the standard click behavior of a button to duplicate it, as it is a bit complex.

You may want to look into UniformGrid to see if that meets your grid needs, since you want to have a variable number of columns and rows. You can set the number of either, and it will flow the children between them. Whatever control you use there, you can place within a ScrollViewer to get the scrolling capabilities.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜