【问题标题】:how to add event handler to control in datatemplate in resource dictionary如何在资源字典中的数据模板中添加事件处理程序以进行控制
【发布时间】:2011-09-07 07:04:56
【问题描述】:

我有一个资源字典:

<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 添加一个事件处理程序。 MainWindowEvents 是一个在文件中定义的类,没有其他类:

Namespace wpfUI2
    Public Class MainWindowEvents

    End Class
End Namespace

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

    <TabControl
        x:Name="Tab1"
        IsSynchronizedWithCurrentItem="True"
        ItemsSource="{Binding}"
        ItemTemplate="{StaticResource ClosableTabItemTemplate}"
        Margin="4"
        SelectionChanged=""
    />

并尝试在“”之间单击以创建事件我收到一条错误消息,指出 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

一切编译正常,但我在 window.show 上遇到运行时异常

我做错了什么?

【问题讨论】:

    标签: wpf event-handling datatemplate resourcedictionary


    【解决方案1】:

    多亏了这个,我才能够让它工作:

    Is it possible to set code behind a resource dictionary in WPF for event handling?

    我发现您的代码中缺少一些东西,与那里的示例进行比较。

    【讨论】:

    • 工作就像一个魅力,谢谢。此外,我发现将资源字典创建为 usercontrol/winow 然后更改 xaml ans cs 文件中的类型更容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 2015-03-13
    相关资源
    最近更新 更多