访问WPF中DataTemplate内的项目

Nil*_*ilu 3 wpf datatemplate

我想知道在WPF中你是否能够获得datatemplate对象的实际实例.例如,在以下情况中:

<UserControl>
    <UserControl.Resources>
        <DataTemplate x:Key="MyTemplate">
            <CustomControl ></CustomControl>
        </DataTemplate>
    </UserControl.Resources>

    <ListBox DataTemplate="{StaticResource MyTemplate}"></ListBox>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

假设CustomControl有一个CustomEvent和一个公众CustomMethod.我想在用户控件中访问该事件和公共方法.这可能吗?我怎么能这样做?在此先感谢您的帮助.

干杯,

尼鲁

hwi*_*ers 5

您需要找到包含ListBox的ContentPresenter(通过导航VisualTree),然后使用

myDataTemplate.FindName("myCustomControl", myListBox);
Run Code Online (Sandbox Code Playgroud)

MSDN上有一个例子:http://msdn.microsoft.com/en-us/library/bb613579.aspx.