访问WPF中DataTemplate内的项目

时间:2009-10-15 21:49:02

标签: wpf datatemplate

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

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

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

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

干杯,

尼鲁

2 个答案:

答案 0 :(得分:0)

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

此博客文章说明了我们可以扩展的一些有用概念:ICommand for Silverlight with Attached Behaviors

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

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

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

通过将它们转换为命令,您可以访问CustomControl的事件。

答案 1 :(得分:0)

我没有在ListBox上看到ItemsSource数据绑定,所以我假设你把它遗漏了。如果你绑定到像ObservableCollection&lt;&gt;这样的东西然后ListBox中的每个项目都有自己的ViewModel类。您可以根据自己的喜好选择公开方法。

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

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

以下是您可能感兴趣的Josh Smith's article on Routed Commands

Apps with MVVM architecture的这篇文章中,Josh描述了自定义ICommands

(这是伪代码)

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();
    }
}