how to add event handler to control in datatemplate in resource dictionary
Asked Answered
G

1

18

I have a resource dictionary:

<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>
...

And I want to add an event handler to the TabControl. MainWindowEvents is a class defined in a file with no other classes:

Namespace wpfUI2
    Public Class MainWindowEvents

    End Class
End Namespace

When I go to add an event handler like

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

and try to click between the "" to create the event I get an error saying that the class specified by the x:Class attribute must be the first in the file. Well it is!. Strangely, when I create the handler manually:

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

Everything compiles ok, but i get a runtime exception on window.show

What am i doing wrong?

Gemini answered 7/9, 2011 at 7:4 Comment(0)
I
11

I was able to make it work thanks to this:

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

I see missing stuff in your code, compare to the sample there.

Indoaryan answered 7/9, 2011 at 7:59 Comment(1)
Worked like a charm, thanks. Also I find it easier to create my resource dictionary as a usercontrol/winow and then change type in xaml ans cs file.Greenwood

© 2022 - 2024 — McMap. All rights reserved.