【问题标题】:How to handle events inside a WPF DataTemplate?如何处理 WPF DataTemplate 中的事件?
【发布时间】:2013-01-15 12:20:08
【问题描述】:

我有一个自定义控件,它有一个名为 ViewModel 的依赖属性,它的值显示在 ContentPresenter 中。对于每种类型的 ViewModel,我都有一个 DataTemplate。每个模板都允许用户以不同的方式进行选择,我需要在后面的自定义控件代码中处理该选择事件。

<Style TargetType="{x:Type local:MyCustomControl}">

    <Style.Resources>
        <ResourceDictionary>

            <DataTemplate DataType="{x:Type local:ViewModelOne}">

                <!-- how to handle this event? -->
                <ListBox
                    MouseDoubleClick="ListBox_MouseDoubleClick"/>
            </DataTemplate>

            <DataTemplate DataType="{x:Type local:ViewModelTwo}">

                <!-- this ListBox has another style, but event should
                     be handled the same way -->
                <ListBox
                    MouseDoubleClick="ListBox_MouseDoubleClick"/>
            </DataTemplate>

            <!-- more templates here -->

        </ResourceDictionary>
    </Style.Resources>

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyCustomControl}">
                <ContentPresenter Content="{TemplateBinding ViewModel}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

编辑:

这是自定义控件背后的代码,以及我希望在双击 ListBox 中的某些内容时调用的方法:

public class MyCustomControl : Control
{
    // how to attach ListBox MouseDoubleClick event to this method? 
    private void ListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        DoMagic(((ListBox)sender).SelectedItem);
    }
}

【问题讨论】:

  • 遇到了同样的问题。你能发布你的实际解决方案吗?

标签: wpf events custom-controls datatemplate


【解决方案1】:

这些数据模板是否在资源字典中定义?

如果是这样,您可以使用attached behaviors

如果它们是在 MyWindow 或 MyUserControl XAML 中定义的,那么您可以在后面的代码中定义它们,即 MyWindow.xaml.csMyUserControl.xaml.cs

【讨论】:

  • DataTemplate 定义在 ResourceDictionary 中属于自定义控件的样式中。但是,如果添加一个附加的行为来挂钩MouseDoubleClick 事件,我如何(在事件处理程序中)将所选项目移动到后面的自定义控件代码?
  • MouseDoubleClick 事件是什么? ListBoxItem?那你已经选择了不是吗?如果您正在处理ListBox.MouseDoubleClickEvent,那么使用((ListBox)sender).SelectedItem 将为您提供所需的一切。
  • 是的,我在后面的代码中使用了发件人的SelectedItem。我的问题是 xaml 无法在后面的代码中找到事件处理程序。我认为这是因为DataTemplate 与自定义控件背后的代码没有直接关系。
  • 在后面添加了一些代码,希望这会使问题更清楚。
猜你喜欢
  • 2013-12-15
  • 2015-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 2011-01-12
相关资源
最近更新 更多