TextBox crop behavior WPF/Silverlight

WPF provides an innovative feature called attached properties, which can be used to add behavior to existing controls. These new properties are not defined on the control being extended, but rather they are defined on a separate object (generally a
DependencyObject). Thus, we end up with a source object that defines the attached properties and a target object on which you attach these properties. The target is the object being extended with new functionality contained in the source. When the attached property is set on the target object, a property change event is fired on the source. The event handler is passed information about the target and the new and old values of the property.
By hooking up property changed handlers, we can add additional behavior by calling methods on the target, changing properties, and listening to events. We look at more detailed examples of using attached properties in Chapter 6, “The Power of Attached Properties.” Keep in mind that attached properties are only a means to extend functionality; the original target control still needs to be considered a “black box,” and its internals cannot be modified.

Let’s consider a simple example that illustrates the use of attached properties. Let’s say you want to display a tooltip on the TextBox when the content in the TextBox is exceeded the size of the available size, note that here we are not going to use the TextWrapping on TextBox instead we simply crop the text at the right end and we will display tooltip when user mover mouse on TextBox.

namespace TextBoxCrop
{
public static class TextBoxCropBehavior
{
public static bool GetTextBoxToolTip(DependencyObject obj)
{
return (bool)obj.GetValue(TextBoxCropToolTipProperty);
}
public static void SetTextBoxToolTip(DependencyObject obj, bool value)
{
obj.SetValue(TextBoxCropToolTipProperty, value);
}

public static readonly DependencyProperty TextBoxCropToolTipProperty = DependencyProperty.RegisterAttached(“TextBoxToolTip”, typeof(bool), typeof(TextBoxCropBehavior), new UIPropertyMetadata(false, OnTextCropChanges));
private static void OnTextCropChanges(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textbox = d as TextBox;
if(textbox != null)
{
textbox.SizeChanged += textbox_SizeChanged;
}
else
{
textbox.SizeChanged -= textbox_SizeChanged;
}

}

static void textbox_SizeChanged(object sender, SizeChangedEventArgs e)
{
var textbox = sender as TextBox;
textbox.Measure(new Size(Double.MaxValue, Double.MaxValue));
var width = textbox.DesiredSize.Width;

if (textbox.ActualWidth < width)
{
ToolTipService.SetToolTip(textbox, textbox.Text);
}
else
{
ToolTipService.SetToolTip(textbox, null);
}
}
}
}

And inside XAML attache the behavior to the control like below:

<Window x:Class=”TextBoxCrop.MainWindow”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
Title=”MainWindow” Height=”350″ Width=”525″
xmlns:local=”clr-namespace:TextBoxCrop”>
<Window.Resources>
<Style TargetType=”TextBox”>
<Setter Property=”local:TextBoxCropBehavior.TextBoxToolTip” Value=”True”/>
<Setter Property=”BorderBrush” Value=”Green”/>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=”Auto”/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=”*”/>
<ColumnDefinition Width=”*”/>
</Grid.ColumnDefinitions>
<TextBox Text=”Textbox with long text Long text long text long text long text” local:TextBoxCropBehavior.TextBoxToolTip=”True” x:Name=”x” HorizontalAlignment=”Right”/>
</Grid>
</Window>

When you run the application you will see the below UI, notice at the TextBox there is a tooltip on it, it is appearing because the text in the Textbox is exceeded the width limit of available size.

Capture

If your application is having similar requirement in more that one view then you can attach the same behavior to a Textbox style and make it implicit so that it will apply to all the Textbox controls.

Below is the example:

<Window x:Class=”TextBoxCrop.MainWindow”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
Title=”MainWindow” Height=”350″ Width=”525″
xmlns:local=”clr-namespace:TextBoxCrop”>
<Window.Resources>
<Style TargetType=”TextBox”>
<Setter Property=”local:TextBoxCropBehavior.TextBoxToolTip” Value=”True”/>
<Setter Property=”BorderBrush” Value=”Green”/>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=”Auto”/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=”*”/>
<ColumnDefinition Width=”*”/>
</Grid.ColumnDefinitions>
<TextBox Text=”Textbox with long text Long text long text long text long text” x:Name=”x” HorizontalAlignment=”Right”/>
</Grid>
</Window>

That’s it 🙂 enjoy coding.

Cheers.

Resize a popup in WPF

Popup control has not build in support for resize. But we can do this by ourself. The following code,

Code Snippet

<Window

   x:Class=”ForumProjects.MainWindow”

   xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

   xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

   Title=”MainWindow” Height=”700″ Width=”800″>

    <StackPanel>

        <Button Click=”ShowPopup”>

            <Grid>

                <TextBlock>Show Popup</TextBlock>

                <Popup Name=”Popup” StaysOpen=”False” Width=”100″ Height=”100″>

                    <Grid Background=”Blue”>

                        <Thumb HorizontalAlignment=”Right”VerticalAlignment=”Bottom” Width=”16″ Height=”16″

                              DragStarted=”onDragStarted”DragDelta=”onDragDelta” DragCompleted=”onDragCompleted”/>

                    </Grid>

                </Popup>

            </Grid>

        </Button>

    </StackPanel>

</Window>

namespace ForumProjects

{

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

        }

        private void ShowPopup(object sender, RoutedEventArgs e)

        {

            this.Popup.IsOpen = true;

        }

        private void onDragStarted(object sender, DragStartedEventArgs e)

        {

            Thumb t = (Thumb)sender;

            t.Cursor = Cursors.Hand;

        }

        private void onDragDelta(object sender, DragDeltaEventArgs e)

        {

            double yadjust = this.Popup.Height + e.VerticalChange;

            double xadjust = this.Popup.Width + e.HorizontalChange;

            if ((xadjust >= 0) && (yadjust >= 0))

            {

                this.Popup.Width = xadjust;

                this.Popup.Height = yadjust;

            }

        }

       private void onDragCompleted(object sender, DragCompletedEventArgs e)

        {

            Thumb t = (Thumb)sender;

            t.Cursor = null;

        }

    }

}

Silverlight Controls Styles

Since many months i have planned to create styles for commonly used sinlverlight controls, but due to busy schedule in office, i didn’t get time to create them, recently i have got some free time and i started creating styles, finally i have taken 2 days of time(Free time).

I have used three base colors for styles and with those colors i have played around the control styling.

Please see the below image for sample, and you can download the sample and view the live one by clicking here

Silverlight UI

Silverlight Alert Box

Recently i have created a alert box in which we can display alert messages or warning messages, i have done this by editing generic Silverlight Child window control. to have the header less window i removed Childwindow’s Chrome part and made some changes in layout system on Child Window . please look in to the below sample image.

For Live sample and Download Click Here

Message Box

 

 

WPF Group Box Style

Recently one of my client asked me to show a good looking group box for our application, so that after a 15 min research i decided to create a group box which will contains a banner at right corner of group box with nice appearance.

I thought it may be useful for others, so i have added this sample in Expression’s Gallery, if you like and wish to use that, download the style and use in your project.

Download Sample project from Here

Sample View:

WPF Group Box

Focus Visual Effect for Text box and Button controls Silverlight

Hello, One day one of my client asked me to give the best effect which is ever implemented , for the application, he gave the best challenging task, and i have taken it as a challenging and started R&D. After 3 days of R&D i have came to create a wonderful style for every Content control of Silverlight, and showed that to the client, he is became mad after seeing that 🙂 , after that he sent a “I phone” for me as a compliment 🙂

I named it as “” Classic Focus Visual “” and  i have applied for Creative common Rights.

I would like to share this wonder full style with all folks. Look at the below sample snap shot of that style in which you can see a small square L shape will appear at four corners.

FocusVisualElementTo view live click here

Difference between Style and Template.

One day my colleague asked(the same question was asked by many people) me about the difference between Style and Template, so i though to explain the difference between these two things by writing a blog post. So that  others can also read this.

Style:

Brief:

Style can be applied to any Silverlight control which is derived from the Framework Element. With the help of style we can modify the default property values of a control for which the style is applied. We can override the property value which are defined in style when we initialize the control on UI. With the help of Style we can specify the default behavior of the control.

Detailed:

The default properties of a controls are defined in <Setter> tag which are defined in the style,

EG:

<Style TargetType=”TextBox” x:Key=”TextboxStyle”>

  <Setter Property=”Background”  Value=”White” />
      <Setter Property=”BorderThickness” Value=”1″ />
<Setter Property=”Template”>
<Setter.Value>

<Setter

</Style>

We can modify the default properties of a control by overriding the properties when we initialize the control on UI.

EX:

<TextBox Background=”Red” Style=”{StaticResource TextboxStyle}”/>

the Background property will changes to red by default it is White which is defined in the style.

Template:

Templates   Used only those elements that inherit from the Control class in the System.Windows.Control namespace.By using  Templates u can modify the structure of the Control to which the Template is applied.Templates      Values can’t be overridden by the values that are set on the control itself when it is drawn on the artboard .But , using Template Binding the property’s  value can set of a template according to the values of a properties of the control when it is drawn on the artboard.When u  Modify with Template u can access to more parts of control then styles.

EX for TemplateL

<ControlTemplate TargetType=”TextBox”>
<Grid x:Name=”RootElement”>

</Grid>
</ControlTemplate>

I hope this may give you basic idea of Template and style.