在WPF中访问DataTemplate内的项

在WPF中访问DataTemplate内的项,wpf,datatemplate,Wpf,Datatemplate,我想知道在WPF中是否能够获得datatemplate对象的实际实例。例如,在以下情况下: <UserControl> <UserControl.Resources> <DataTemplate x:Key="MyTemplate"> <CustomControl ></CustomControl> </DataTemplate> </UserCo

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

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

    <ListBox DataTemplate="{StaticResource MyTemplate}"></ListBox>
</UserControl>

假设
CustomControl
具有
CustomEvent
和公共
CustomMethod
。我想访问该事件和用户控件中的public方法。这可能吗?我怎样才能做到这一点?提前感谢您的帮助

干杯


Nilu

您可以创建一个附加到CustomControl并与之交互的对象

这篇博客文章阐述了一些我们可以扩展的有用概念:

因此,您可以创建一个附加到自定义控件的类,而不是附加到按钮的单击事件(在WPF中已经有了命令)

按照引用的博客文章中的模式,您最终会得到:

<CustomControl 
  MyNamespace:CustomControlCommand.EventCommand=
  "{Binding Path=CommandHandler}" />


这将使您能够通过将CustomControl的事件转换为命令来访问它们。

您需要找到持有列表框的ContentPresenter(通过导航VisualTree),然后使用

myDataTemplate.FindName("myCustomControl", myListBox);

MSDN上有一个示例:。

我在列表框中没有看到ItemsSource数据绑定,因此我假设您忽略了它。如果绑定到类似ObservableCollection的对象,则列表框中的每个项都将有自己的ViewModel类。您可以根据自己的喜好在这些问题上使用公共方法

如果希望处理自定义控件中的事件,请在最低级别的代码隐藏中处理它,在本例中是在UserControl的代码隐藏中

然后,在每个ViewModel中都有一个ICommand实例(或者一个路由命令,如果适合您的目的)。在UserControl中有一个DataContext,可以将其转换为ViewModel的类型。因此,事件处理程序可以访问ViewModel并执行命令

这是你可能会感兴趣的

在上的这篇文章中,Josh描述了自定义iCommand

(这是伪代码)


@itowlson:来自列表框所在的用户控件。当a事件触发时,我想从usercontrol调用一个自定义方法(包含在CustomControl中)。通过VisualTree(通常不是您想要的)和更好的解决方案,我回答了问题“[如何]获取datatemplate对象的实际实例。”问题标题为“访问WPF中数据模板内的项目“毕竟。就我所见,这是做这件事的标准方法。投票支持这个答案,因为这是我发现这个问题时所寻找的答案。这可能不是最好的方式,提供替代方案也不错,但这并不是否决投票的理由,因为这显然是对所问问题的正确答案。
class ViewModelType {
    public void DoSomething() { /* ... */ }
    public ICommand DoSomethingCommand { get; set; }
    public string Property { get; set; }
}

class CodeBehind {
    public void EventHandler(object, args) {
        (DataContext as ViewModelType).DoSomethingElseCommand.Execute();
    }
}