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
Here's some XAML that works in Kaxaml:
You would change the
Page
object with yourUserControl
. I find it much easier to test these sorts of things out in a rapid prototyping tool such as Kaxaml before coding up theUserControl
in VS.Note that you have to set the default colour (in this case
#CCCCD0
) via a property setter and not via an attribute on thePage
itself. This is because the attribute would override the value set by the trigger (because it's a style trigger), so even though the trigger would fire, it would always be trumpted by the local attribute specification, meaning that it wouldn't change. I only point this out because it's a fairly common gotcha.If you were changing the background of the text box you need to remove the
TargetName
property:and change the TextBox that wants this style to be:
However, as you want to change the value of the parent user control this won't give you want you want.
You could certainly do it in the code behind by adding a
GotFocus
event handler and putting the code to change the background colour in there.Will it work to wrap the contents of your
UserControl
inside aBorder
object? If so, you can simply style theBorder
like so:Update: (Answering Sheraz' Questions)
I'm not sure why
ElementName
doesn't work for accessing children within aUserControl
. It might have something to do with the way the visual tree is constructed.As for
Trigger
vsDataTrigger
: 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 theDataTrigger
there and have it watch theTextBox
than to have theTextBox
change the appearance of theBorder
.As I understand it, the
TargetName
property ofSetter
is only applicable within aDataTemplate
orControlTemplate
. (Info from Dr. WPF in this forum post)