How to get x:Name value runtime

我是研究僧i 提交于 2019-12-01 09:13:57

问题


I got:

   <ListView.View GridViewColumnHeader.Click="ColumnHeaderClick">
      <GridView>
          <GridViewColumn x:Name="Col" Header="Item">   



   private void ColumnHeaderClick(object sender, RoutedEventArgs e)
     {
        GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;

     }

Now, how to get the x:Name value of GridViewColumn in the method? I can't put 'Name' property for the column in xaml, and it comes like empty string in runtime. Although I am able to get the header, still need to get x:Name value.


回答1:


When you use the x:Name syntax on an element that isn't a FrameworkElement or FrameworkContentElement, it registers the element with a NameScope. Unfortunately, you can't retrieve the name for an element, the lookup only works the other way around.

If you need to pass additional information about the DataGridColumn, a custom attached property would be an easy way of doing it.

More information about x:Name can be found on MSDN. Also, the NameScope documentation describes its behavior.




回答2:


You can leverage reflection to grab the value with:

GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
String xName = (String)headerClicked.getType().GetProperty("Name").GetValue(headerClicked, null);


来源:https://stackoverflow.com/questions/2526357/how-to-get-xname-value-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!