This is a mirror of official site: http://jasper-net.blogspot.com/

A Silverlight Resizable TextBlock (and other resizable things)

| Tuesday, March 22, 2011
In this blog post I present a simple attached behaviour that uses a Thumb control within a Popup to adorn any UI element so that the user can re-size it.

A simple feature that has become quite popular on the web is to attache a small handle to text areas so that the user can resize them, this is useful if a user wants to add a large piece of text to a small comment form for example. Interestingly the Google Chrome browser makes all text areas resizeable by default, which leads to web developers wondering how to turn this feature off for their website. I thought that this was a pretty useful feature, so decided to implement a little attached behaviour that would do the same think for Silverlight:

You can make any element resizable by setting the following attached property:

<TextBox Text="This is a re-sizeable textbox"
          local:ResizeHandle.Attach="True">
</TextBox>

The implementation of this behaviour is pretty straightforward. When the Attach property changes, i.e. when it is set on an element a Thumb and a Popup are created:

private static Dictionary<FrameworkElement, Popup> _popups =
    new Dictionary<FrameworkElement, Popup>();
 
private static void OnAttachedPropertyChanged(DependencyObject d,
  DependencyPropertyChangedEventArgs e)
{
  FrameworkElement element = d as FrameworkElement;
 
  // Create a popup.
  var popup = new Popup();
 
  // and associate it with the element that can be re-sized
  _popups[element] = popup;
 
  // Add a thumb to the pop-up
  Thumb thumb = new Thumb()
  {
    Style = Application.Current.Resources["MyThumbStyle"] as Style
  };
  popup.Child = thumb;
 
  // add a relationship from the thumb to the target
  thumb.Tag = element;
 
  popup.IsOpen = true;
 
  thumb.DragDelta += new DragDeltaEventHandler(Thumb_DragDelta);
  element.SizeChanged += new SizeChangedEventHandler(Element_SizeChanged);
}

A static dictionary is used to relate the elements which have this property set o their respective Popup. The Thumb is styled via a Style which is looked up from the application resources. The following style re-templates the Thumb, replacing its visuals with an image:

             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml
             x:Class="ResizableTextBox.App">
  <Application.Resources>

Read more: ScottLogic

Posted via email from Jasper-net

0 comments: