微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/101045.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐