How to set an event handler on the ContentTemplate that is defined in a resource file?
window xaml
<!-- this doesnt get triggered -->
<Style x:Key="TabControlEventSetter" TargetType="{x:Type TabControl}">
<EventSetter Event="SelectionChanged"
Handler="TabControl_SelectionChanged"/>
</Style>
<!-- headered content control containing tab control -->
<HeaderedContentControl
x:Name="WorkspaceTabControl"
Header="Workspaces"
Style="{StaticResource MainHCCStyle}"
Content="{Binding Path=Workspaces}"
ContentTemplate="{StaticResource WorkspacesTemplate}"
/>
resource xaml
<!-- configure content area -->
<Style x:Key="MainHCCStyle" TargetType="{x:Type HeaderedContentControl}">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="{TemplateBinding Content}" />
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type HeaderedContentControl}">
<DockPanel>
<ContentPresenter
DockPanel.Dock="Top"
ContentSource="Header"
ContentTemplate="{TemplateBinding HeaderTemplate}"
/>
<ContentPresenter
ContentSource="Content"
ContentTemplate="{TemplateBinding ContentTemplate}"
/>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Render a Tab Control -->
<DataTemplate x:Key="TabItemTemplate">
<DockPanel >
<ContentPresenter
Content="{Binding Path=DisplayName}"
VerticalAlignment="Center"
/>
</DockPanel>
</DataTemplate>
<!-- Render Workspace -->
<DataTemplate x:Key="WorkspacesTemplate">
<TabControl
IsSynchronizedWithCurrentItem="True"
ItemTemplate="{StaticResource TabItemTemplate}"
ItemsSource="{Binding}"
>
<TabControl.Resources>
<Style TargetType="TabItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabItem">
<ContentPresenter
x:Name="ContentSite"
ContentSource="Header"
/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.Resources>
</TabControl>
</DataTemplate>
window xaml cs
private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sender is TabItem tab)
{
// handle tab change event
}
}
tried defining a style as suggested here... Is there Selected Tab Changed Event in the standard WPF Tab Control which doesnt seem to work.
so, is there a way in xaml to "attach" an event handler to a "contentTemplate" that is defined in a separate resource xaml?
CodePudding user response:
If you define the Style
as an implicit one without an x:Key
, it will be applied to all TabControl
controls in scope that don't have any specific Style
applied to them:
<HeaderedContentControl
x:Name="WorkspaceTabControl"
Header="Workspaces"
Style="{StaticResource MainHCCStyle}"
Content="{Binding Path=Workspaces}"
ContentTemplate="{StaticResource WorkspacesTemplate}">
<HeaderedContentControl.Resources>
<Style TargetType="{x:Type TabControl}">
<EventSetter Event="SelectionChanged"
Handler="TabControl_SelectionChanged"/>
</Style>
</HeaderedContentControl.Resources>
</HeaderedContentControl>