Silverlight 4 Nuevas Características – Drag & Drop

Una de las nuevas funcionalidades que nos traerá Silverlight 4 es la característica Drag & Drop. Hoy en día los usuarios entienden como algo natural las acciones de Drag & Drop. Ahora cualquier control que derive de UIElement viene con los eventos DragEnter, DragLeave, DragOver y Drop, ya no tenemos que crearnos nuestro manejador de drag & drop con los eventos MouseLeftButtonDown, MouseMove y MouseLeftButtonUp, lo cual era un engorro y nada elegante.

Una de las acciones mas clásicas que se pueden realizar en Silverlight con Drag & Drop es arrastrar una imagen de nuestro explorador de ficheros a un elemento de nuestra aplicación Web, es una acción mas natural que lo que teníamos que hacer antes. Vamos a ver con un ejemplo como se realizaría

A un objeto Canvas vamos a permitir realizar al usuario que arrastre un archivo de imagen y esta se visualice en el Canvas

 

   1:  <Canvas x:Name="DropCanvas" AllowDrop="True" Drop="DropCanvas_Drop" >

Con esto ya permitimos que se pueda realizar el Drop y tenemos el evento, solo nos falta tratarlo

   1:  private void DropCanvas_Drop(object sender, DragEventArgs e)
   2:  {
   3:      IDataObject dataObject = e.Data;
   4:      Point dropPoint = e.GetPosition(DropCanvas);
   5:      if (dataObject.GetDataPresent(DataFormats.FileDrop))
   6:      {
   7:          FileInfo[] files = (FileInfo[])dataObject.GetData(DataFormats.FileDrop);
   8:          
   9:          if (files.Length > 0)
  10:          {
  11:              if (files[0].Extension == ".jpg")
  12:              {
  13:                  
  14:                  System.Windows.Media.Imaging.BitmapImage bitmapImage = 
  15:                      new System.Windows.Media.Imaging.BitmapImage();
  16:                  bitmapImage.SetSource(files[0].OpenRead());
  17:                  Image newImage = new Image();
  18:                  newImage.Source = bitmapImage;
  19:                  newImage.Width = 200;
  20:                  newImage.Height = 200;
  21:   
  22:                  newImage.SetValue(Canvas.TopProperty, dropPoint.Y);
  23:                  newImage.SetValue(Canvas.LeftProperty, dropPoint.X);
  24:   
  25:                  newImage.Stretch = Stretch.Uniform;
  26:                  DropCanvas.Children.Add(newImage);
  27:              }
  28:          }
  29:      }
  30:  }
  31:   

 

Como podéis ver muy sencillo

Videos How-To de WPF4

Han salido una serie de videos de menos de 15 minutos que nos cuentan las nuevas características que vienen en WPF 4, son en Ingles pero altamente recomendables

What’s New in Windows Presentation Foundation 4

  • New Windows Presentation Foundation Controls. This video introduces three new controls in WPF – DataGrid, Calendar and DatePicker. You’ll see how each new control is used in a quick demonstration.
  • Visual State Manager was originally introduced in Silverlight to provide a better way to manage states and transitions for visual controls. With the release of .NET 4.0, WPF now supports the Visual State Manager –in this brief video you’ll see how the VSM is used in a WPF application.
  • Touch comes to Windows Presentation Foundation. With the introduction of new touch and multi-touch monitors and laptops, developers have a new opportunity in application development. To support this opportunity, WPF now supports built-in touch gestures; in this video, see how these gestures can be used in a simple WPF application.
  • Graphics Enhancements. WPF 4 introduces new improvements in the graphics system – in this short video, you’ll see how layout rounding helps render blurry or semi-transparent edges. You’ll see how cached composition improves rendering time and how WPF supports Pixel Shader 3.

A partir del 18 de Enero:

  • Binding in Windows Presentation Foundation 4 has evolved with improvements to InputBinding and the introduction of the IDynamicMetaObjectProvider interface. In this short video you’ll see how these work in a set of simple examples.
  • XAML Browser Applications (XBAPs) can now communicate with their hosting Web page, and (if the user allows) they can be installed as full trust applications. In this video see how each of these two new features is implemented in WPF 4.
  • Windows Presentation Foundation and Windows 7.  The new Windows 7 taskbar provides new types and functionality that you can leverage from your WPF 4 application. In this video see how you can create custom Jump List functionality for a WPF application running in Windows 7.
  • Windows Presentation Foundation Designer. In this brief video you’ll see how the WPF and Silverlight Designer has been enhanced in Visual Studio 2010 to support multiple platform versions, visual data binding, auto layout and improved property editing.

Enlaces Interesantes Silverlight/WPF 13-01-2010

 

Los del día

 

  • Extensibility Series – WPF & Silverlight Design-Time Code Sharing – Part II (Karl Shifflett)
  • Silverlight Spy 3.0.0.7 (Koen Zwikstra)
  • Silverlight 4 Beta & MEF – Experimenting with an alternative Programming Model and Silverlight 4 – Displaying a Bunch of Files from a Zip File (Mike Taulty)
  • Digging into Data (from a XAML perspective) (Rob Relyea)
  • Silverlight Top 10 of 2009 (Silverlight Team)
  • Severely Decoupled Configuration (Jesse Liberty)
  • Minimizing your designer footprint (Alex Knight)
  • How SilverUnit can help you be famous (Roy Osherove)
  • Silverlight : MVVM Library and File Upload (Sacha Barber)
  • Using the Model View Presenter pattern in WPF (Paul Stovell)
  • Migrating from Silverlight Streaming to Windows Azure (Mike Ormond)
  • Synchronous Invocation of Delegates with the Silverlight Dispatcher (Daniel Vaughan)
  • Debugear Una Aplicación Out of Browser sin Atachar el Proceso

    El titulo lo dice todo, como podemos debugear una aplicación de silverlight 4  Out Of Browser sin tener que “atachar” el proceso a Visual Studio sino con F5 directamente (mucho mas cómodo). Lo primero que tenemos que hacer es instalar la aplicación en el escritorio

     

    image

    image

     

    Una vez instalada en el escritorio, vamos a las propiedades de la aplicación Silverlight y elegimos en la pestaña de Debug la opción Installed out-of-browser-application

     

    image

    El siguiente paso es poner como proyecto de inicio nuestra aplicación Silverlight en vez de la web y pulsar F5 y se ejecutara en modo out-of-browser parándose en todos los breakpoints que pongamos.

     

    Espero que os ayude

    Enlaces Interesantes Silverlight/WPF 11-01-2010

    Os dejo los enlaces de hoy

     

  • Sketching, painting and Figure drawing (Pavan Podila)
  • A WPF Behavior for Window Resize Events in .NET 3.5 (Pete Brown)
  • Silverlight : MVVM Library and File Upload (Sacha Barber)
  • Silverlight – About validation when binding to custom forms – Part 2 using Silverlight 4 (Fredrik Normen)
  • Promoting reuse using Behaviors: RotateRefreshBehavior (Bob Bartholomay)
  • Fluent Silverlight – static reflection and Fluent Silverlight – Table of content (Gabriel N. Schenker)
  • Silverlight 4 Nuevas Características – ClipBoard

    Otra de las nuevas características que nos trae Silverlight 4 es interactuar con el Portapapeles para poder copiar y pegar texto en nuestras aplicaciones silverlight. Esta caracteristica viene implementada a través de 3 métodos estáticos de la clase ClipBoard, estos son:

    • Clipboard.SetText()
    • Clipboard.ContainsText()
    • Clipboard.GetText()

    El método SetText envía texto al portapapeles, un ejemplo seria Clipboard.SetText(TextBlock.Text);. Este método funciona tanto en aplicaciones in-browser y out-of-browser, solo que en la aplicaciones in-browser nos mostrará un mensaje advirtiéndonos y preguntando al usuario si quiere dejar copiar el texto al portapapeles.

     

    image

    En las aplicaciones out-of-browser al ejecutarse en un entorno full trusted no lo pregunta. Para copiar el texto utilizaremos el método GetText

     

       1:  private void PasteButton_Click(object sender, RoutedEventArgs e)
       2:  {
       3:      if (Clipboard.ContainsText())
       4:      {
       5:          PasteTexArea.Selection.Text = Clipboard.GetText();
       6:      }
       7:      else
       8:      {
       9:          WarningTextBlock.Text = "No hay texto en el portapapeles";
      10:      }
      11:  }

     

    Por ahora en esta versión solo se permite copiar texto, esperemos que en la definitiva nos permitan copiar y pegar imágenes

    Mostrar Tooltip Cuando los controles están deshabilitados en WPF

    Esta fue una pregunta de los foros y la respuesta es bien sencilla (una vez que la conoces), solo tienes que poner a true la propiedad “attached” ToolTipService.ShowOnDisabled y nos mostrara el Tooltip aunque el control este deshabilitado. Los Tooltip ademas  de esta propiedad tiene otras mas para manejarlos como por ejemplo

    ToolTipService.HasDropShadow="False"
    ToolTipService.InitialShowDelay="100"
    ToolTipService.ShowDuration="5000"
    ToolTipService.ShowOnDisabled="True"
    ToolTipService.Placement="Bottom"

    Enlaces Interesantes Silverlight/WPF 08-01-2010

    Aqui viene una nueva remesa d epost interesantes

     

  • Silverlight – About validation when binding to custom forms (Fredrik Normen)
  • Silverlight and styles (Gabriel N. Schenker)
  • Silverlight 4 OOB: Please remove the My-Folders restriction. It doesn’t work anyways. (Ingo Rammer)
  • The ultimate hack for Silverlight in Blend (Josh Smith)
  • Fonts and Silverlight (Koen Zwikstra)
  • iMeta Agility & Silverlight (Mike Taulty)
  • Extending the SLHVP Player to be a Platform (Jesse Liberty)
  • Bing Maps 3D, WPF, and Windows 7 MultiTouch (Marc Schweigert)
  • Silverlight 4 Beta – More on MEF and the PackageCatalog (Mike Taulty)
  • Silverlight – Navigate to a specific Page using a Hyperlink (Fredrik Normén)
  • Retransmisión del concierto de Alicia Keys con Silverlight

    Uno de los puntos fuertes de Silverlight es sin duda el Streaming, en mi opinión es muy bueno y quedo demostrado con las olimpiadas, en este caso tenemos un ejemplo mas que es el concierto que Alicia Keys va a dar en el teatro Apollo hoy a las 6pm PST (si mi conversión es buena las 3:00 de la mañana de esta noche). Según parece el usuario podrá elegir su propio ángulo de cámara de los 5 que se van a utilizar, de manera que te vas a convertir en un realizador del concierto de Alicia Keys.

    Además  podrá ser visto por Iphone e Ipod tal como se demostró en el PDC

    Aquí podéis ver el video promocional

    PD: para ver el concierto podeis ir a http://live.billboard.com/Concert/View/200230

    Silverlight/WPF behavior Para Añadir Multitouch e Inercia

    Esto es algo que tenia en mente intentar realizar cuando sacase algo de tiempo, pero me alegro que alguien como Davide Zordan lo haya sacado y compartido con nosotros, se trata de un behavior que nos da soporte Multitouch con inercia, tal y como funciona en la Surface, simplificándonos bastante  si queremos dar un toque de Multitouch a nuestras aplicaciones, podéis ver el articulo completo esta dirección.

    El código del behavior esta disponible en la Expression Community gallery

     

     

    image