I have a simple user control with a TextBox. I want to change the color of user control when the TextBox gets the focus. This is what I have:
<UserControl x:Class="OutLookContactList.ContactSearchControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="root" MinHeight="30" Loaded="UserControl_Loaded">
<UserControl.Resources>
<Style x:Key="searchTextBoxStyle" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="IsFocused" Value="true">
<Setter TargetName="root" Property="Background" Value="{StaticResource OnMouseOverColor}" />
</Trigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
But I get the errot “TargetName property cannot be set on a style Setter”. How can I Set the back ground color of user control when text box gets the focus?
Thanks a bunch
Will it work to wrap the contents of your
UserControlinside aBorderobject? If so, you can simply style theBorderlike so:Update: (Answering Sheraz’ Questions)
I’m not sure why
ElementNamedoesn’t work for accessing children within aUserControl. It might have something to do with the way the visual tree is constructed.As for
TriggervsDataTrigger: Trigger is for dependency properties and DataTrigger is for databound properties (data or other controls). Since you are trying to style theBorder, it makes more sense to place theDataTriggerthere and have it watch theTextBoxthan to have theTextBoxchange the appearance of theBorder.As I understand it, the
TargetNameproperty ofSetteris only applicable within aDataTemplateorControlTemplate. (Info from Dr. WPF in this forum post)