Getting an object reference by name from a DataTemplate

随声附和 提交于 2019-12-21 20:45:41

问题


If I have the following XAML:

<toolkit:DataForm Height="100"  x:Name="form">
        <toolkit:DataForm.EditTemplate>
            <DataTemplate>
                <StackPanel Name="stack"></StackPanel>
            </DataTemplate>
        </toolkit:DataForm.EditTemplate>
    </toolkit:DataForm>
I can get a reference to "form" by this.FindName("form") from the View.

How can I get a reference to "stack"? FindName returns null.


回答1:


The problem here is that the xaml content of a DataTemplate belongs to a different NameScope than the outer Xaml. Calling FindName on an element searches only the NameScope in which the element was originally generated. Hence calling FindName on the UserControl will not find elements generated by a DataTemplate. The reason for this is that DataTemplate (and other templates) are designed to be reused multiple times, the use of NameScope disambiguates the names.

The solution is to invoke the help of the VisualTreeHelper, have a look at the code in this blog for my take on VisualTreeHelper. With the VisualTreeEnumeration class from that blog added to your project you can do this:-

var element = this.Descendents().OfType<FrameworkElement>().FirstOrDefault(fe => fe.Name == "stack");

Of course if you know that "stack" is a StackPanel then you can get more specific with .OfType<T>.



来源:https://stackoverflow.com/questions/6137967/getting-an-object-reference-by-name-from-a-datatemplate

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