How to access x: property-name in code?

I assigned x: Name in my XAML file to an object that can trigger the MouseDown event. In this case, I want to get the x: name-attribute of the sender again. How to do it?

The object is as follows:

<ModelUIElement3D MouseDown="ModelUIElement3D_MouseDown" x:Name="trololo"> 
0
source share
2 answers

If I understand your question correctly, you can access the Name property by sending a sender to FrameworkElement .

Alternatively, you can simply use the reference object created by the constructor; the instance name matches the name specified in the x:Name attribute.

Both options are shown below.

  private void ModelUIElement3D_MouseDown(object sender, MouseButtonEventArgs e) { var element = sender as FrameworkElement; if (element != null) { if (element.Name == "trololo") { } } // Or if (sender == trololo) { } } 
+5
source

The Name property based on FrameworkElement is a standard dependency property intended as a shortcut for x: Name (see the FrameworkElement.Name property ). However, many dependency objects are not inferred from FrameworkElement, and yet they can still use the X: Name property attached to XAML. To determine x: Name at runtime of an object declared in XAML that is not the result of FrameworkElement, you can get a property attached to the object using GetValue, as shown below:

 foreach(var column in gridItem.ColumnDefinitions) { var name = column.GetValue(FrameworkElement.NameProperty) as string; if (name == "IsCheckedColumn") column.Width = show ? CheckUncheckColumn_VisibleWidth : Column_InvisibleWidth; else if (name == "DeleteColumn") column.Width = show ? DeleteColumn_VisibleWidth : Column_InvisibleWidth; } 
0
source

All Articles