从C#网格控件获取单元格内容

时间:2010-12-17 08:33:09

标签: wpf c#-3.0 controls wpf-controls

我在C#应用程序中使用 System.Windows.Controls.Grid 。加载表单后,我在单元格中添加了UIElement s。但是当我点击单元格时,如何获取当前的UIElement

PS:我在网上搜索过,发现我们需要遍历UIElementCollection并获取值。

但这不是一个好主意。因为,如果我们有1000个单元格并且它有1000个媒体元素,那么我需要循环遍历所有UIElement。所以建议我如何获得内容。

我的代码片段:(试用)

          private void DispImage(System.Windows.UIElement uiElement)
          {
              foreach (var item in this.grid1.Children)
                {
                    if (item is textBox1)
                    {
                        element = item;
                        break;
                    }
                }
                if (element != null)
                {
                    this.grid1.Children.Remove(element as UIElement);
                }

                if (uiElement != null)
                {
                    Grid.SetRow(uiElement, CurrentRow);
                    Grid.SetColumn(uiElement, CurrentColumn);
                if (this.DynamicGrid.Children.IndexOf(UIElement) == -1)
                    this.DynamicGrid.Children.Add(uiElement);
               }
            }

此处UIElementImageObject

1 个答案:

答案 0 :(得分:0)

您遇到了麻烦,因为您使用 WPF 以非常旧的方式使用 WinForms 方式。

熟悉模型 Bindings 命令等概念,它将很好地解决。

在你的情况下,它意味着:

  • 为您的商品创建模型并将其放入模型集合中
  • 将您的模型绑定到模板ItemsControl,并使用适当的ItemsPanel
  • 为在UIElement
  • 中包裹Button的商品定义模板
  • 实现Command做任何你想做的事
  • Command分配给Button
  • ???
  • 利润

更一般地说,直接修改用户界面:修改模型并让用户界面与之交互。