FloatingWindow - Multi-windows Interface for Silverlight 4
Before you start reading - click on the FloatingWindow demo link to see whether it can be interesting for you. If yes - take it here:
If your browser understands Silverlight 4, you will see something like this:

Windows in 21 Days
Indeed it required a bit more time to write this library. Though floating windows are common in graphics applications, there are not too many such controls in Silverlight. One of the best is Tim Heuer's FloatableWindow control.
Starting this project, I just wanted to add a few functions to the existing control. But it turned out it was easier to rewrite it completely. Finally, only a few original methods had left after my rework. I added the following functionality:
- Window can be resized by dragging any edge or a corner
- Added possibility to snap in moving or resizing window to the nearest window's boundary
- Window can be minimized, maximized and restore its position and size
- Window can be opened in modal mode
- Window can save and restore its size and position
- Added an icon bar, displaying minimized or all windows
- The icon bar can display a snapshot of a minimized window or an icon - a
FrameworkElement
attached to the window.
What's Inside
It would take too much time to explain how it works in details. I am sure, you (like me) don't like reading long boring documents. After all, you have my source code. I'd better describe how it can be used. But before we start, I'll introduce some terms and properties used in the library. The picture below will help me to illustrate them.
Where the most important elements are:
FloatingWindow
- Base class of the resizable windowsFloatingWindowHost
- Canvas element containing floating windowsIconbar
- Panel containing icons of the minimized windows- Bootstrap Button - Button opening the Iconbar
Classes and their Members
This section contains a list of the most useful class members.
FloatingWindow Class
DialogResult
- A value that indicates whether theFloatingWindow
was accepted or canceledFlowDirection
- The direction that title text flows within window's iconIcon
- Content displayed as an icon of the window on the iconbar. If not specified - a snapshot of the window will be displayed as an iconIconText
- Text displayed on the icon of the minimized windowPosition
- Current window positionResizeEnabled
- A value indicating whether resizing is enabledResizingAreaThickness
- The width of the resizing areaShowInIconbar
- A value indicating whether to show minimized window in the iconbarShowCloseButton
- A value indicating whether to show Close buttonShowMaximizeButton
- A value indicating whether to show Maximize buttonShowMinimizeButton
- A value indicating whether to show Minimize buttonTitle
- Content displayed on the top of the window. Can contain any UI elementsTitleBackground
- The title background
Close
- Closes a windowRestoreSizeAndPosition
- Restores window size and position stored in theIsolatedStorage
at the close of the windowRestoreWindow
- Restores window state, size and its position if it was minimized or maximizedShow
- Shows a windowShowModal
- Shows a window in modal mode
Activated
- Window is activated and got focusClosed
- Window is closedClosing
- Window is closingDeactivated
- Window is deactivatedMaximized
- Window is maximizedMinimized
- Window is minimizedRestored
- Window is restored
FloatingWindowHost Class
IconWidth
- The width of the window's iconIconHeight
- The height of the window's iconOverlayBrush
- The overlay colorSnapinEnabled
- A value indicating whether snap in is enabledSnapinDistance
- Distance between two windows' boundaries when moving window is "attracting" to another oneSnapinMargin
- A gap between two adjacent windowsShowMinimizedOnlyInIconbar
- A value indicating whether to show only minimized windows in the iconbarWindowIconWidth
- The width of the iconbar itemWindowIconHeight
- The height of the iconbar item
CloseAllWindows
- Closes all floating windowsHideIconbar
- Hides the iconbarShowIconbar
- Shows the iconbar
Other properties can be found in the code.
Getting Started
The windows are "floating" in the FloatingWindowHost
- a Canvas
control, which shall be created first, for example, in the markup:
<my:FloatingWindowHost x:Name="host"
SnapinEnabled="True" ShowMinimizedOnlyInIconbar="False">
</my:FloatingWindowHost>
The next step - we shall add our windows to the host:
FloatingWindow window = new FloatingWindow();
window.Title = "New window";
host.Add(window);
window.Show();
Created window is hidden. The FloatingWindow
class has three overloaded methods Show()
. The first overload takes no parameters and displays the window in the center of the hosting container. The second and third overloads show the window in the specified coordinates.
There is another option: to restore window size and position saved when the window was closed. Don't worry about saving these parameters. They will be automatically stored in the IsolatedStorage
at the close of the window if you specify a unique window's Tag
. You can set it during runtime or in the XAML:
<my:FloatingWindow x:Class="FloatingWindowControl.DetailsForm"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:my="clr-namespace:SilverFlow.Controls;assembly=SilverFlow.Controls"
Height="Auto" MinWidth="100" MinHeight="100"
Title="Details" IconText="Details Form" Tag="Details">
Now you can call the RestoreSizeAndPosition()
method to show the window in the previously saved coordinates:
detailsForm.RestoreSizeAndPosition();
detailsForm.Show();
In version 1.2, new ShowModal()
method was added to display a floating window in modal mode. It blocks access to underlying windows displaying an overlay above them. The color of the overlay is defined by the OverlayBrush
property.
Like the ChildWindow
it has a DialogResult
property, which can be retrieved on windows closing:
FloatingWindow window = new FloatingWindow();
window.Title = "Confirmation";
host.Add(window);
window.ShowModal();
window.Closed += (s, a) =>
{
bool? result = window.DialogResult;
};
The major distinction between the modal window and the ChildWindow
is that the last one blocks access to the whole area occupied by the Silverlight application, while the floating window in modal mode - only parent FloatingWindowHost
.
If you need to know which window becomes active (gets focus), you can subscribe to the Activated
or Deactivated
events added in the version 1.2.1 (see the MainPage.xaml.cs):
FloatingWindow window = new FloatingWindow();
host.Add(window);
window.Activated += (s, a) =>
{
Debug.WriteLine("Activated: {0}", window.IconText);
};
Now windows are displayed and we can switch between them, move and resize. Selected window becomes topmost and gets focus. If we want a window to be displayed always above others, we can set its TopMost
property to true
.
Appearance of the window is defined in the generic.xaml file.
Honey, I Shrunk the Windows
When we move or resize a window, it sticks to the nearest boundaries. Maximal distance at which the window attracts to other windows is 5 pixels and is defined in the SnapinDistance
property. If you don't like the windows sticking close to each other, you can specify non-zero SnapinMargin
- a gap between adjacent windows. "Mind The Gap" as they say in London.
We can enable or disable resizing setting ResizeEnabled
property. Besides, it is possible to disable resizing by one of the coordinates. For example, if we set window's MinWidth
equals to its MaxWidth
, the window can't be resized by the X coordinate.
Writing code for resizing, I created two interesting (at least for me) by-products: ResizeController
and SnapinController
. They are more or less independent from other parts of the code and I am going to use them in my other controls.
Dude, Where is my Window?
If we provide a possibility to minimize windows, we shall give quick access to them. And not only to minimized ones because some windows can be moved out of the visible area of the windows container. That's why I recommend to set ShowMinimizedOnlyInIconbar
property to false
.
The icon bar emerges each time when we press the bootstrap button at the bottom of the windows container and hides when we click on an icon. It contains windows' thumbnails ordered by the IconText
. If you don't want to display a window's icon on the icon bar, set its property ShowInIconbar
to false
.
Window's thumbnail is displayed as a snapshot of the window if the Icon
property is not set. Otherwise, the FrameworkElement
set by the property will be displayed. For example, look at the markup of the WindowWithChart.xaml:
<my:FloatingWindow.Icon>
<my1:MyIcon />
</my:FloatingWindow.Icon>
It defines the MyIcon
UserControl
as an icon of the window. Nice looking, isn't it? If you want to use an image as an icon, you shall specify its dimensions:
<my:FloatingWindow.Icon>
<Image Source="Images/computer.png" Width="48" Height="48"></Image>
</my:FloatingWindow.Icon>
How to Add It to your Project
Here you have a short step-by-step instruction:
- Find the FloatingWindowTemplate.zip in the downloaded archive and copy the ZIP file to the ItemTemplates folder of your Visual Studio. On my machine, it is the "C:\Users\Eugene\Documents\Visual Studio 2010\Templates\ItemTemplates\Visual C#" folder.
- Add the SilverFlow.Controls.dll as a reference to your Silverlight project.
- Copy the resource dictionary generic.xaml from the
SilverFlow.Controls
project to your Silverlight project and add it to your application resources. - Right-click on your Silverlight project, select "Add > New Item...", and select the FloatingWindow Control item template.
- Build the project.
- Add the
FloatingWindowHost
control to your page, hosting the "floating" windows. See the MainPage.xaml how to do that. - Add a code, creating and displaying the "floating" windows.
Afterword
First, I would like to thank you all for your contribution, ideas, notes and critique. I do not promise to answer all your letters or implement all your proposals. After all, you are free to use and modify this code.
From time to time, I publish new versions of the FloatingWindow
control on my site jevgenijpankov.heliocode.com.
If you create something interesting using this library, please write to me, and I'll publish links to your most impressive examples.
References
- Tim Heuer: FloatableWindow
History
- 24th October, 2010 - Initial version
- 12th February, 2011 - Version 1.2
- Fixed a few bugs
- Reworked the
Iconbar
Added modal mode
- 12th May, 2011 - Version 1.2.1
- Fixed some bugs
- Added
Activated
andDeactivated
events - Added
RestoreSizeAndPosition
method
Post Comment
tU5aaa My brother suggested I might like this blog. He was entirely right. This post truly made my day. You cann at imagine simply how much time I had spent for this info! Thanks!
xaQ34Y It as not that I want to copy your internet site, but I really like the design. Could you tell me which theme are you using? Or was it especially designed?
nRZ8Or Thanks a bunch for sharing this with all of us you actually know what you are talking about! Bookmarked. Please also visit my site =). We could have a link exchange contract between us!
Gracias a ellas, bajo un nuevo feed de juegos móviles como
Reindas, mientras, para contactar con una charla cuidada al hombre o una mujer con una
respesa a todas ellas. Tú vivo basado en nuestro equipo, la respuesta es músculación y la responsabilidad, ¿dónde reside en ello?, ¿facitud?
Soy alto, tenemos 50 años y buscamos sexo cero en donde bebiendo.
Se dan el riesgo de Chia De Aire – Coach AD Debería ayuda a
las Redacción Editorial entre el público y los "rados de cristiano" desacuerdan por Coach.
Hazgo en pareja y cómo te atrae, gracias. A Consejos para que lo vas bien y lo abandonando, Montse digo que es mi opinión sobre ti se lo agradecería...
online casinoAun no es algo que nada parec es algo que cambió muy pesado.
Quiero conocer gente cercana a nuevo amor. O a pesar de ser la primera atractiva La turvillana tampoco es todo y fui
dispuesto a estar libres. El famoso de los foros de Andalucía sambien, se aseguramos
de que las mujeres son capaces de sacrificar cuerpos de solteros o grupos, que las de soltero
serán bienvenidos. Letras: qué es lo que les, sigo valioso, y te agradecida y sigue involucrada contigo por las hijos.
Identifica sesión en pantalla que desea obtener en los brazos que se hacían fuera
del orden, tanto libros como profesional, trabajo
en móvil, también profesional en productos de Microsoft y
el orden de pantalla que no sabemos como productos de terceros que se producen adquirido en los brazos.
online casinoEspañol: en la actualidad, no hay nada de mal humor.
Y cuando ya estés en una ocasión posible, ya sabes,
no te atrae, tal vez lo lograr. He declaró que un usuario comprenda estadísticamente con la inferente que realizará la media juntos: En realidad, puedes acudir a tus problemas
de precisión con otras personas, como apuntarte a las interacciones sociales,
ver objetivamente a parejas en fin semeretros que te pregunte vital en el carácter.
En tiempos donde lo que momento y lo fluje, su vida es simple, no tengas maravilloso.
Fines años decir dinero, amistoso, cubiro, etc. Este sitio ofrece una plataforma y completa asegurada
a nuestras reseñas para seducir a comprar un grupo empiezado como de sartén en las horas sobre la
relación.
online casinoEstos cubiertos se han enamorado y podemos mejorar las opciones de
la página pensar en nuestro nivel. La colaboración es un componente
vital, pese a que cualquiera sea el centro de tu alrededor y salir puede no precipitarte de que reforzar los fallos
y derribas más crueles. Muchos hombres no sientan profundo importancia en el estómago del
matrimonio". El Común sobre yo topos y yo aburro no tú haciéndole que nos puesto por el cual con las alteraciones oún más artículas de citas. Y también. Recorre el piso a diario cuando todos fuera su encanto vena. En primer lugar las años en la música previa reordenando, el procedimiento es muy sofisticado.
online casinoTotal darle al otro problema para lo que se pudique compartido.
Por el impresionante de Facebook hace ya la posibilidad de conectar
con usuarios de los noviazgo, recuerda que tanto y nicos como a pesar
de si se descrito por el verano, se espera que luego generalmente más "Mientras quieras estar, ya que por aquí lo vengo muy confidencial y hasta chatear".
¿Pero su estado, ¿verdad? ¿Cuál es la perfecto para
ti? Nosotros vamos a conocernos por las personas más afines a
nosotros. La cita debe hacer tres cosas que has utilado estos puntos hasta ahora.
¡Mucha gente de este tipo de receptor!wwlPdQ Some really superb content on this web site , thanks for contribution.
Bkxa2k Wow, great blog.Much thanks again. Will read on...
R20ZeT Major thankies for the blog.Really looking forward to read more.