【发布时间】: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