Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you override just part of a control template in silverlight

Tags:

silverlight

Is it possible to change or modify a specific part of a control template without having to recreate the entire control template of the control in the xaml?

For example, I was trying to get rid of the border of a textbox, so I could throw together a basic search box with rounded corners (example xaml below). Setting the borderthickness to 0 works fine, until you mouse over the textbox and a pseudo border they added to the control flashes up. If I look at the controltemplate for the textbox, I can even see the visual state is named, but cannot think of how to disable it.

Without overriding the control template of the TextBox, how would I stop the Visual State Manager firing the mouse over effect on the TextBox?

<Border Background="White" CornerRadius="10" VerticalAlignment="Center" HorizontalAlignment="Center" BorderThickness="3" BorderBrush="#88000000">
    <Grid VerticalAlignment="Center" HorizontalAlignment="Center" Width="200" Margin="5,0,0,0">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="16" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Path Height="13" Width="14" Stretch="Fill" Stroke="#FF000000" StrokeThickness="2" Data="M9.5,5 C9.5,7.4852815 7.4852815,9.5 5,9.5 C2.5147185,9.5 0.5,7.4852815 0.5,5 C0.5,2.5147185 2.5147185,0.5 5,0.5 C7.4852815,0.5 9.5,2.5147185 9.5,5 z M8.5,8.4999971 L13.5,12.499997" />
            <TextBox GotFocus="TextBox_GotFocus" Background="Transparent" Grid.Column="1" BorderThickness="0" Text="I am searchtext" Margin="5,0,5,0" HorizontalAlignment="Stretch" />
    </Grid>
</Border>
like image 707
mattmanser Avatar asked Apr 23 '09 15:04

mattmanser


1 Answers

I've found a way to do this, by inheriting off the control and overriding the OnApplyTemplate. It's not ideal, but I think it's better than having to copy the entire control template. Here's an example of creating a borderless textbox, essentially disabling the mouse over visual state by always clearing the storyboard:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace SilverlightTestApplication
{
    public class BorderlessTextBox  : TextBox
    {
        public BorderlessTextBox()
        {
            BorderThickness = new System.Windows.Thickness(0);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            //Get the mouse over animation in the control template
            var MouseOverVisualState = GetTemplateChild("MouseOver") as VisualState;

            if (MouseOverVisualState == null)
                return;

            //get rid of the storyboard it uses, so the mouse over does nothing
            MouseOverVisualState.Storyboard = null;
        }
    }
}
like image 96
mattmanser Avatar answered Oct 06 '22 00:10

mattmanser