【问题标题】:ItemsControl Children Events WPF C#ItemsControl 子事件 WPF C#
【发布时间】:2011-07-28 09:49:42
【问题描述】:

我在 ItemsControl 中有 225 个三状态切换按钮(关闭、垂直、水平),排列在 15 * 15 的统一网格中。有没有办法找到选中的按钮,它的选中状态和位置?只是一点背景,我正在开发一个类似拼字游戏的游戏。

例如。如何找到红场的状态和位置?

  1. 当用户单击 Tile 时,我想触发程序记录其索引的事件在这种情况下,例如。 57 或 7,3
  2. 那么当用户输入他们的 Word 时,是否可以在 ToggleButton State(垂直、水平)方向实时预览字符?但是尚未将 ItemsControl 绑定到 ObservableCollection 中?

非常感谢

【问题讨论】:

  • 你只能取出你放入的东西。你有没有在你的方块上附加任何东西来识别它们的顺序?您可以找到正方形的 x/y 位置,但这不一定是可靠或可维护的方法。

标签: c# wpf xaml


【解决方案1】:

我会通过 DataBinding 解决这个问题(就像其他所有问题一样)。

让我们首先定义我们的视图模型:

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

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

并将其分配给您的用户控件或窗口并创建复选框:

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

【讨论】:

    【解决方案2】:

    您应该能够遍历 ItemsControl 的子控件,然后对于循环中的每个项目,检查按钮的状态,如果已选中,则检索其位置。

    此链接会有所帮助:

    How do I access the children of an ItemsControl?

    【讨论】:

      猜你喜欢
      • 2010-12-08
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 2013-04-13
      • 1970-01-01
      • 2013-06-15
      相关资源
      最近更新 更多