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

Gil*_*lit 16 wpf datatemplate event-handling 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">
    <TabControl
        x:Name="Tab1"
        IsSynchronizedWithCurrentItem="True"
        ItemsSource="{Binding}"
        ItemTemplate="{StaticResource ClosableTabItemTemplate}"
        Margin="4"/>
</DataTemplate>
...
Run Code Online (Sandbox Code Playgroud)

我想为TabControl添加一个事件处理程序.MainWindowEvents是在没有其他类的文件中定义的类:

Namespace wpfUI2
    Public Class MainWindowEvents

    End Class
End Namespace
Run Code Online (Sandbox Code Playgroud)

当我去添加一个事件处理程序时

    <TabControl
        x:Name="Tab1"
        IsSynchronizedWithCurrentItem="True"
        ItemsSource="{Binding}"
        ItemTemplate="{StaticResource ClosableTabItemTemplate}"
        Margin="4"
        SelectionChanged=""
    />
Run Code Online (Sandbox Code Playgroud)

并尝试在""之间单击以创建事件我收到一条错误,指出x:Class属性指定的类必须是文件中的第一个.好吧!奇怪的是,当我手动创建处理程序时:

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
Run Code Online (Sandbox Code Playgroud)

一切都编译好,但我在window.show上得到一个运行时异常

我究竟做错了什么?

Nat*_*txo 10

由于这个原因,我能够让它成功:

是否可以在WPF中为资源字典设置代码以进行事件处理?

我看到你的代码中缺少的东西,与那里的样本相比.