如何从DataGridColumn获取DataGridColumnHeader?
我的代码如下:
void mainDataContextObj_CutSelectedColumnEvent(string columnId)
{
IList<DataGridColumn> columns = dg.Columns;
for(int i=2; i<dg.Columns.Count; i++)
{
DataGridColumnHeader headerObj = dg.Columns[i].Header as DataGridColumnHeader;
//This always returns headerObj as null!!!
}
}
我需要列中的 DataGridColumnHeader
。我哪里错了?
My code is as follows:
void mainDataContextObj_CutSelectedColumnEvent(string columnId)
{
IList<DataGridColumn> columns = dg.Columns;
for(int i=2; i<dg.Columns.Count; i++)
{
DataGridColumnHeader headerObj = dg.Columns[i].Header as DataGridColumnHeader;
//This always returns headerObj as null!!!
}
}
I need DataGridColumnHeader
from the column. Where am I going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DataGridColumn 的 Header 对象实际上是该列的可见标题,无论您将其设置为什么。 DataGridColumn 不是可视化树的一部分,因此没有直接的方法来访问它的 DataGridColumnHeader(我们甚至无法确定它是否存在)。但你可以做这样的事情来尝试访问它
The Header object of the DataGridColumn is actually the visible header of that column, whatever you set it to be. DataGridColumn is not part of the Visual Tree so there is not direct way to access the DataGridColumnHeader for it (we can't even be sure it exists yet). But you can do something like this to try and access it
虽然Fredrik的答案提供了一种重构方法,其中包含可能在代码的其他部分重用的附加方法,但我更喜欢合并他的方法整合为一种方法。还可能有一些小的性能增益,因为它可以在找到标题后立即结束搜索,并且不需要继续搜索可视化树中的所有子级(在大多数情况下这很可能可以忽略不计)。
它的使用方式如下:
While Fredrik's answer provides a refactored approach with additional method that could potentially be reused in other parts of the code, I preferred to consolidate his methods in to one single method. There may also be some small performance gain because it can end the search as soon as it finds the header and it does not need to continue to search through all the children in the visual tree (this is most likely negligible for most cases).
And it is used like so: