値が内に表示される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);
}
}