TargetType does not match element type

I have a simple buttonStyle defined for TargetType of Button ; but setting the style to the button gives release.

 <Window> <Window.Resources> <Style x:Key="buttonStyle" TargetType="{x:Type Button}"> <Setter Property="Background" Value="Magenta"/> </Style> </Window.Resources> <StackPanel Orientation="Horizontal"> <Button Content="1" FocusVisualStyle="{StaticResource buttonStyle}"/> </StackPanel> </Window> 

Additional information: 'Button' TargetType does not correspond to the type of the Control element.


Also, setting TargetType as Control resolves the runtime error, but the visual style of the button does not change when it receives Focus .


Style works when installing Button.Style


Edit I have two specific questions:

  • I agree that FocusVisualStyle is a property of FrameworkElement and FrameworkContentElement , but why is there a button to set an error on the button, even though the style is the name of the style and not the typed style

  • Why is FocusVisualStyle not displayed on Button ? Is Button.FocusVisualStyle internally with any higher priority value such as templates, triggers or template triggers?

+5
source share
2 answers

a FocusVisualStyle allows you to visualize user feedback while focusing control . For example, adding a Rectangle that looks like the border of a control.

A Style is the appearance of the control itself. All this explains here .

FocusVisualStyle not a style for Button itself; it is a style when Button focused.

See here for more details.

I think you are after Trigger .

 <Style x:Key="buttonStyle" TargetType="{x:Type Button}"> <Style.Triggers> <Trigger Property="IsFocused" Value="True"> <Setter Property="Background" Value="Magenta"/> </Trigger> </Style.Triggers> </Style> 

Then you can set the Style your Button , for example:

 <Button Style="{StaticResource buttonStyle}" ... /> 
+5
source

You should use it like this:

  <Style x:Key="buttonStyle" TargetType="{x:Type Button}"> <Style.Triggers> <Trigger Property="IsFocused" Value="True"> <Setter Property="Background" Value="Magenta" /> </Trigger> </Style.Triggers> </Style> 

and install it like this:

 <Button Content="1" Style="{StaticResource buttonStyle}"/> 

To see it better:

  <Style x:Key="buttonStyle" TargetType="{x:Type Button}"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="Magenta" /> </Trigger> </Style.Triggers> </Style> 

From MSDN

The visual focus style feature provides a general β€œobject model” for introducing visual feedback from the user based on keyboard navigation to any element of the user interface. This is possible without applying the new template to control or know the specific composition of the template.

+1
source

All Articles