1

I have 225 three state toggle buttons(Off, Vertical, Horizontal) within a ItemsControl arranged in a 15 * 15 uniformgrid. Is there any way to find the checked button, its checked state and its position? Just a little background i'm working on a scrabble-like game.

enter image description here

eg. how do i find the the state and position of the Red Square?

  1. When the user clicks the Tile I want to fire an event where the program records it's index In this case eg. 57 or 7,3
  2. Then as the user inputs their Word, is it possible for the characters to be previewed live in the direction of ToggleButton State (Vertical, Horizontal)? However not written into the ObservableCollection the ItemsControl is bound to yet?

Thanks Alot

H.B.
  • 166,899
  • 29
  • 327
  • 400
Tony Wu
  • 329
  • 1
  • 6
  • 15
  • You can only get out what you've put in. Have you attached anything to your squares that identify their order? You could find the x/y position of the square, but that's not necessarily a reliable or maintainable way to do it. – Dan Puzey Jul 28 '11 at 09:57

2 Answers2

1

I would solve this (like everything else) through DataBinding.

Lets first define our viewmodel:

public class ScrabbleViewModel
{
  readonly bool[,] matrix = new bool[15,15];

  public bool[,] GameMatrix
  {
      get { return matrix; }
  }
}

and assign it to your usercontrol or window and create the checkboxes:

public partial class GameWindow : Window
{
  public GameWindow()
  {
    InitializeComponent();
    this.DataContext = new ScrabbleViewModel();
    CreateCheckBoxes();
  }

  void CreateCheckBoxes()
  {
    for(int y=0;y<15;y++)
    {
      for (int x = 0; x < 15; x++)
      {
        var chk = new CheckBox();
        chk.SetValue(Grid.RowProperty, y);
        chk.SetValue(Grid.ColumnProperty, x);

        var binding = new Binding(string.Format("GameMatrix[{0},{1}]", y, x));
        binding.Mode = BindingMode.TwoWay;
        chk.SetBinding(CheckBox.IsCheckedProperty, binding);

        grid.Children.Add(chk);
      }
    }
  }
}
Oliver Weichhold
  • 10,259
  • 5
  • 45
  • 87
0

You should be able to loop through the children controls of the ItemsControl and then for each item in the loop, check the state of the button and if it is checked, then retrieve its position.

This link will help:

How do I access the children of an ItemsControl?

Community
  • 1
  • 1
Mamta D
  • 6,310
  • 3
  • 27
  • 41