从 C# 网格控件获取单元格内容
我在 C# 应用程序中使用 System.Windows.Controls.Grid 。加载表单后,我在单元格中添加了 UIElement。但是当我单击单元格时,如何取回当前的 UIElement
?
PS:我搜索了网络,发现我们需要循环 UIElementCollection
并获取值。
但这不是一个好主意。因为,如果我们有 1000 个 Cell,并且它有 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);
}
}
这里 UIElement
是一个 ImageObject
。
I am using System.Windows.Controls.Grid in C# application. When the form is loaded, I added the UIElement
s in the cells. But when I click the cell, how do I get the current UIElement
back?
PS: I searched the web, and I found out we need to loop through the UIElementCollection
and get the values.
But this is not a good Idea. Because, if we have 1000 Cells and it has 1000 media elements, then I need to loop through all the UIElement
s. So suggest me how we will get the content.
My code Snippet:(Trial)
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);
}
}
Here UIElement
is an ImageObject
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您遇到了麻烦,因为您以一种非常古老的方式(WinForms)使用WPF。
熟悉诸如模型、绑定、命令等概念,它会很好地解决。
在您的情况下,这意味着:
ItemsControl
,并使用适当的ItemsPanel
UIElement
包装在Button
中Command
来执行您希望它执行的任何操作Command
分配给你的按钮
以更一般的方式,不要直接修改用户界面:修改模型并让用户界面与其交互。
You had troubles because you're using WPF in a very old style, WinForms way.
Get familiar with concepts such as Models, Bindings, Commands and it will solve nicely.
In your case it means:
ItemsControl
, with appropriateItemsPanel
UIElement
in aButton
Command
to do whatever you want it to doCommand
to yourButton
In a more general way, do not modify the user interface directly: modify your model and let the user interface interact with it.