我有一个自定义控件,它有一个名为ViewModel的依赖项属性,它的值显示在ContentPresenter
中。对于每种类型的DataTemplate
,我都有一个ViewModel。每个模板允许用户以不同的方式进行选择,我需要在后面的自定义控制代码中处理该选择事件。
<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);
}
}
发布于 2013-01-15 12:23:54
这些DataTemplates是否在资源字典中定义?
如果是这样的话,您可以使用附随行为。
如果它们是在MyWindow或MyUserControl XAML中定义的,那么您可以定义它们背后的代码,即MyWindow.xaml.cs
或MyUserControl.xaml.cs
https://stackoverflow.com/questions/14337595
复制相似问题