c# – 如何访问x:代码中的Name-property – 对于非FrameworkElement对象?

another question类似,我想通过代码访问对象的x:Name属性,在这种情况下,有问题的对象不是FrameworkElement,因此没有Name属性.我也无法访问成员变量.

在我的情况下,我有一个带有命名列的ListView,并希望扩展ListView类,以便它保持列布局.对于这个功能,我需要命名列,因为其他原因重新使用我需要设置的x:Name属性是有意义的,而不是添加附加的“ColumnName”属性.

我目前的“解决方案”:

<GridViewColumn Header="X" localControls:ExtendedListView.ColumnName="iconColumn" />

期望:

<GridViewColumn Header="X" x:Name="iconColumn" />

那么有可能以某种方式获得“x:Name”值吗?

解决方法

请参阅IanG在以下主题中的答案:
How to read the x:Name property from XAML code in the code-behind

Unfortunately,that’s not quite what x:Name does. x:Name isn’t
technically a property – it’s a Xaml directive. In the context of a
.NET WPF application,x:Name means this:

“I want to be able to have access to this object via a field of this
name. Also,if this type happens to have a name property,please set
it to that name.”

It’s that second part that you need,and unfortunately that second
part doesn’t apply to ModelUIElement3D,because that type doesn’t have
a property to represent the name. So in effect,all it means is “I
want to be able to have access to this object via a field of this
name.” And that’s all.

因此,所有x:Name都可以通过创建具有该特定名称的字段来访问此对象.如果要获取x:它的名称,则必须迭代所有字段并查看该字段是否是您要查找的对象,返回字段名称.

他确实提出了一种在代码隐藏文件中执行此操作的方法,尽管我认为您当前使用附加属性方法一个更好的解决方

public string GetName(GridViewColumn column)
{
    var findMatch = from field in this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                    let fieldValue = field.GetValue(this)
                    where fieldValue == column
                    select field.Name;

    return findMatch.FirstOrDefault();
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...