0

I would like to set Triggers for the controls in a DataTemplate. Whenever I set a property of the control within the DataTemplate, it seems not working. However, If do not set the property within the TextBlock inside the DataTemplate, then I can see the effect of Trigger in the style (it works). I am not sure whether using Style Triggers with DataTemplate is good or not! The XAML is below;

<Grid> <Grid.Resources> <Style TargetType="TextBlock" x:Key="BlockOf"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="FontWeight" Value="ExtraBold" /> <Setter Property="FontSize" Value="22" /> </Trigger> </Style.Triggers> </Style> </Grid.Resources> 

...........

DataTemplate for the button,

<Button.ContentTemplate> <DataTemplate DataType="Button"> <TextBlock Style="{DynamicResource BlockOf}" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}" FontStyle="Italic" FontSize="9"/> </DataTemplate> </Button.ContentTemplate> 
0

1 Answer 1

1

I can see two problems here. First one is that current trigger will work only for TextBlock inside Button, not over whole Button. You can change that by using DataTrigger with RelativeSource binding. Second problem is that even when mouse is over TextBlock Style.Trigger cannot overwrite local value that you set against TextBlock so you need to bring default values as Setter into your Style. Check Dependency Property Setting Precedence List

<Style TargetType="TextBlock" x:Key="BlockOf"> <Setter Property="FontStyle" Value="Italic"/> <Setter Property="FontSize" Value="9"/> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=IsMouseOver}" Value="True"> <Setter Property="FontWeight" Value="ExtraBold" /> <Setter Property="FontSize" Value="22" /> </DataTrigger> </Style.Triggers> </Style> 

and then TextBlock simply

<TextBlock Style="{DynamicResource BlockOf}" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}" /> 
Sign up to request clarification or add additional context in comments.

2 Comments

" First one is that current trigger will work only for TextBlock inside Button, not over whole Button", that's what I want. I just want to use IsMouseOver for the TextBlock inside the button. However, for the second problem I think you are right. So in order to work with Style Triggers, I should avoid local values and set them via Style Setters for ex., right?
Sorry, I just assumed it's wrong. If that's desired behaviour then your trigger is fine just don't set local values

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.