Tuesday, May 8, 2007

Target an inner element from setter

Consider a scenario where we need to change the second color of a gradient on mouse over.The normal solution will be as follows.

<Button>
<Button.Template>
<ControlTemplate TargetType="Button">
<Rectangle Width='60' Height='40' x:Name='MyRectangle'>
<Rectangle.Fill>
<LinearGradientBrush >
<GradientStop Color='Red' />
<GradientStop Color='Blue' Offset='1' x:Name='SecondStop' />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName='MyRectangle' Property="Fill" >
<Setter.Value>
<LinearGradientBrush >
<GradientStop Color='Red' />
<GradientStop Color='Green' Offset='1' />
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>

If we folllow this method we need to write the same code twice.If there is a method to change the value of second color directly,it would be more easier to code.The below code does it with the help of binding.


<Button>
<Button.Template>
<ControlTemplate TargetType="Button">
<Rectangle Width='60' Height='40' x:Name='MyRectangle'>

<Rectangle.Tag>
<Color>Blue</Color>
</Rectangle.Tag>

<Rectangle.Fill>
<LinearGradientBrush >
<GradientStop Color='Red' />
<GradientStop Color='{Binding ElementName=MyRectangle, Path=Tag}' Offset='1' x:Name='SecondStop' />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName='MyRectangle' Property="Tag" Value="Green" >
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>

No comments:

Post a Comment