简体   繁体   中英

ItemsControl Children Events WPF C#

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.

在此处输入图片说明

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

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);
      }
    }
  }
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM