在我的情况下,我有一个带有命名列的ListView,并希望扩展ListView类,以便它保持列布局.对于这个功能,我需要命名列,因为其他原因重新使用我需要设置的x:Name属性是有意义的,而不是添加附加的“ColumnName”属性.
我目前的“解决方案”:
<GridViewColumn Header="X" localControls:ExtendedListView.ColumnName="iconColumn" />
期望:
<GridViewColumn Header="X" x:Name="iconColumn" />
那么有可能以某种方式获得“x:Name”值吗?
解决方法
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(); }