Wpf 如何在资源字典的datatemplate中向控件添加事件处理程序

Wpf 如何在资源字典的datatemplate中向控件添加事件处理程序,wpf,event-handling,datatemplate,resourcedictionary,Wpf,Event Handling,Datatemplate,Resourcedictionary,我有一本资源字典: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="wpfUI2.MainWindowEvents"> <DataTemplate x:Key="WorkspacesTemplate">

我有一本资源字典:

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="wpfUI2.MainWindowEvents">


<DataTemplate
    x:Key="WorkspacesTemplate">
    <TabControl
        x:Name="Tab1"
        IsSynchronizedWithCurrentItem="True"
        ItemsSource="{Binding}"
        ItemTemplate="{StaticResource ClosableTabItemTemplate}"
        Margin="4"/>
</DataTemplate>
...
当我添加一个事件处理程序时,比如

    <TabControl
        x:Name="Tab1"
        IsSynchronizedWithCurrentItem="True"
        ItemsSource="{Binding}"
        ItemTemplate="{StaticResource ClosableTabItemTemplate}"
        Margin="4"
        SelectionChanged=""
    />
一切都可以编译,但window.show上出现运行时异常


我做错了什么?

多亏了以下几点,我才能够让它正常工作:


与那里的示例相比,我发现您的代码中缺少了一些内容。

非常有效,谢谢。此外,我发现将资源字典创建为usercontrol/winow,然后更改xaml ans cs文件中的类型更容易。
    <TabControl
        x:Name="Tab1"
        IsSynchronizedWithCurrentItem="True"
        ItemsSource="{Binding}"
        ItemTemplate="{StaticResource ClosableTabItemTemplate}"
        Margin="4"
        SelectionChanged=""
    />
Namespace wpfUI2
    Public Class MainWindowEvents
        Public Sub Tab1_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs)

        End Sub
    End Class
End Namespace