How to access x: Property-name in code - for non FrameworkElement objects?

Like another question , I would like to access the x: Name property of an object through code, hard in this case the object in question is not a FrameworkElement and therefore does not have a Name property. I also do not have access to the member variable.

In my situation, I have a ListView with named columns and would like to extend the ListView class so that it retains the layout of the column. For this function, I need named columns, and for me it would be advisable to reuse the x: Name property, which I need to set for other reasons, instead of adding the attached ColumnName property, for example.

My current "solution":

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

Desired:

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

So is it possible to somehow get the value of "x: Name"?

+7
source share
1 answer

See the answers from IanG in the following thread:
How to read x: Name property from XAML code in code below

Unfortunately, this is not exactly what x: Name is. x: The name is not a technical property - it is a Xaml directive. In the context of a .NET WPF application, x: Name means the following:

"I want to have access to this object through the field of this name. Also, if this type has a name property, set it to that name."

This is the second part that you need, and, unfortunately, this second does not apply to ModelUIElement3D, since this type does not have a property to represent the name. Thus, all this means: "I want to have access to this object through the field of this name." And that’s all.

Thus, all x: Name does what it gives you access to this object, creating a field with that specific name. If you want to get the name x: Name, you will need to iterate over all the fields and see if the field is the object you are looking for, in which case return the field name.

It provides a method for doing this in the code behind the file, although I think your current approach with an attached property is a much better solution

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

All Articles