October 1, 2012 08:06 by
Scott
Microsoft has just officially released the highly anticipated Windows Server 2012. The newly released server operating system offers a number of features that can be utilized to benefit developers, resellers and businesses. As a premier European Windows and ASP.NET hosting provider that follow the developments of Microsoft products, HostForLIFE.eu proudly announces the support of Windows Server 2012 Hosting Platform in the world-class Amsterdam (The Netherlands) data center.
“We know that our customers are always looking for new technologies and the latest Microsoft product. With the launch of Windows Server 2012, we believe that anyone can take advantage of all the improvements available in this platform”, said Manager of HostForLIFE.eu, Kevin Joseph. “The focus on high availability, scalability, and virtualization has made this one of the most important releases of Windows Server to date. We have been working closely with Microsoft throughout the pre-release development cycle of the platform to both drive the direction of the product and ensure our team is ready to support Server 2012 solutions. We couldn’t be more excited and confident in the solutions now available to our clients with Windows Server 2012.”
With our Windows Server 2012 Hosting Platform, customers have an access directly to all the newest technologies and frameworks, such as ASP.NET 4.5 Hosting, ASP.NET MVC 4 Hosting, Silverlight 5 Hosting, WebMatrix Hosting, Visual Studio Lightswitch Hosting and SQL 2012 Hosting. All these technologies/frameworks are integrated properly on our world-class Control Panel. The package is offered from just €2.45/month and we believe that this is the most affordable, features-rich Windows and ASP.NET Hosting package in European market.
HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.microsoft.com/web/hosting/HostingProvider/Details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.
For more information about our service, please visit http://www.hostforlife.eu.
About HostForLIFE.eu:
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.
Our number one goal is constant uptime. Our data center uses cutting edge technology, processes, and equipment. We have one of the best up time reputations in the industry.
Our second goal is providing excellent customer service. Our technical management structure is headed by professionals who have been in the industry since its inception. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.
September 28, 2012 09:03 by
Scott
Another cool feature available in Silverlight 5 is markup extensions. The idea behind the feature is ability to allow developers to supply values to XAML parser at the time it parses visual tree. In other words, once parser finds a markup extension in XAML, it will create an instance of it, set any properties that the extension might have, then call ProvideValue method that will return a value of the type that the property that markup extension supports expects. For example, I am writing a markup extension to supply an ICommand to the button, my XAML would looks like the following:
<Button Content="Save" HorizontalAlignment="Left"
Grid.Row="4" Grid.Column="0"
Command="{ext:CommandMarkupExtension
ViewModel={Binding ElementName=LayoutRoot, Path=DataContext},
ExecuteMethodName=Run,
CanExecuteMethodName=CanRun}"/>
So, in this example for markup extension I am writing a command extension. As you can see in the XAML above, my extension takes three parameters: ViewModel to invoke, execute and can execute method names. This way I can de-clutter my view model by removing all the command instantiation code, and just write the two methods I need. The code in this extension is very easy – just a handful of dependency properties and interface implementation for IMarkupExtension:
using System;
using System.Windows;
using System.Windows.Input;
using System.Xaml;
namespace SL5Features.Extensions
{
public class CommandMarkupExtension : FrameworkElement, IMarkupExtension<ICommand>
{
public Object ViewModel
{
get { return (Object)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
public static readonly DependencyProperty ViewModelProperty =
DependencyProperty.Register(
"ViewModel", typeof(Object),
typeof(CommandMarkupExtension),
new PropertyMetadata(null));
public string ExecuteMethodName
{
get { return (string)GetValue(ExecuteMethodNameProperty); }
set { SetValue(ExecuteMethodNameProperty, value); }
}
public static readonly DependencyProperty ExecuteMethodNameProperty =
DependencyProperty.Register(
"ExecuteMethodName",
typeof(string),
typeof(CommandMarkupExtension),
new PropertyMetadata(null));
public string CanExecuteMethodName
{
get { return (string)GetValue(CanExecuteMethodNameProperty); }
set { SetValue(CanExecuteMethodNameProperty, value); }
}
public static readonly DependencyProperty CanExecuteMethodNameProperty =
DependencyProperty.Register(
"CanExecuteMethodName",
typeof(string),
typeof(CommandMarkupExtension),
new PropertyMetadata(null));
public ICommand ProvideValue(IServiceProvider serviceProvider)
{
ReflectionCommand command =
new ReflectionCommand(ViewModel, ExecuteMethodName, CanExecuteMethodName);
return command;
}
}
}
To support the extension I need to write a command object that would actually implement ICommand. This class is pretty trivial, so I am not commenting it much:
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
namespace SL5Features.Extensions
{
public class ReflectionCommand : ICommand
{
private MethodInfo canExecuteMethod = null;
private MethodInfo executeMethod = null;
private object viewModel = null;
private ReflectionCommand() {
public ReflectionCommand(
object viewModel,
string executeMethodName,
string canExecuteMethodName)
{
this.viewModel = viewModel;
Type type = viewModel.GetType();
if (!string.IsNullOrEmpty(canExecuteMethodName))
{
this.canExecuteMethod = type.GetMethod(canExecuteMethodName);
}
this.executeMethod = type.GetMethod(executeMethodName);
}
public void Execute(object parameter)
{
executeMethod.Invoke(viewModel, new[] { parameter });
}
public bool CanExecute(object parameter)
{
if (viewModel != null && canExecuteMethod != null)
{
return (bool)canExecuteMethod.Invoke(viewModel, new[] { parameter });
}
else
{
return true;
}
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
}
So, far it is pretty easy. Now, all I have to do is add Run and CanRun method on my view model that my command will invoke:
using SL5Features.Models;
using System.Windows;
namespace SL5Features.ViewModels
{
public class PersonViewModel : ViewModelBase<Person
{
public PersonViewModel()
{
Model = new Person() { FirstName = "Sergey", LastName = "Barskiy" };
}
public void Run(object parameter)
{
MessageBox.Show("Run")
}
public bool CanRun(object parameter
{
return true;
}
}
}
Hopefully, I demonstrated the power of markup extension for you. The goal of using them to me is reduction of the amount of code elsewhere in the system, since you will obviously have to write more XAML. Of course, I am sure Blend 5 will support mark up extensions, so potentially you can just drag my extension on top of the button and setup a few properties in properties window. You will also see a number of demos where an extension is used to support localization, which seems pretty intuitive use of the feature. Bottom line is: I love getting new features that make my job easier by allowing me to write less code and re-use more of the code written.
September 4, 2012 07:09 by
Scott
Now Visual studio 2011 is giving IntelliSense for WCF config files (App.config, Web.config). It is really good for .NET developer, previously when we developed WCF application; Application development is easy rather than configuration. Now in VS 2011 gives us IntelliSense in the Config file. Even we can also map contract.
In previous version of Visual Studio we did configuration via " Edit WCF Configuration" wizard
In the below image we can set endpoint binding.
In the below image we can set service contract.
August 28, 2012 10:00 by
Scott
If you have done any WPF application development I am sure you have used and fallen in love with the Static markup extension. If you’re are not familiar with it, the Static markup extension allows you to reference static fields and properties in your XAML markup.
For example; let’s assume we have a class with the following static field defined:
public class Common
{
public static string StaticText = "This is text from a static property";
}
We can use this field in our WPF application as follows:
<Grid>
<TextBlock Text="{x:Static ext:Common.StaticText}" />
</Grid>
NOTE: “ext” is a namespace that has been defined to instruct the XAML parser where to find our static field.
Pretty cool right? Unfortunately if you are also doing any Silverlight development you will soon find that this wonderful and useful extension does NOT exist in Silverlight. Luckily for us in Silverlight 5 we were given the ability to write our own custom markup extensions. This can be done using either the IMarkupExtension or the abstract MarkupExtension class.
Now it’s time to create our own Static markup extension. I want to point out that there is a naming convention when creating custom markup extensions. The convention is as follows; ExtensionNameExtension. The name of the extension is followed by Extension. This is very similar to how you create attributes. You won’t actually be using the suffix when define them in XAML.
Let’s start by creating a new class called StaticExtension. The StaticExtension class should derive from the MarkupExtension abstract class. You will need to implement the abstract ProvideValue method. The code I used for the Static markup extension is as follows.
/// <summary>
/// Class for Xaml markup extension for static field and property references.
/// </summary>
public class StaticExtension : MarkupExtension
{
/// <summary>
/// The static field or property represented by a string. This string is
/// of the format Prefix:ClassName.FieldOrPropertyName. The Prefix is
/// optional, and refers to the XML prefix in a Xaml file.
/// </summary>
private string _member;
public string Member
{
get { return _member; }
set
{
if (value == null)
{
throw new ArgumentNullException("Member");
}
_member = value;
}
}
/// <summary>
/// Return an object that should be set on the targetObject's targetProperty
/// for this markup extension. For a StaticExtension this is a static field
/// or property value.
/// </summary>
/// <param name="serviceProvider">Object that can provide services for the markup extension.
/// <returns>
/// The object to set on this property.
/// </returns>
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (_member == null)
throw new InvalidOperationException("member cannot be null");
// Validate the _member
int dotIndex = _member.IndexOf('.');
if (dotIndex < 0)
throw new ArgumentException("dotIndex");
// Pull out the type substring (this will include any XML prefix, e.g. "av:Button")
string typeString = _member.Substring(0, dotIndex);
if (typeString == string.Empty)
throw new ArgumentException("typeString");
// Get the IXamlTypeResolver from the service provider
IXamlTypeResolver xamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
if (xamlTypeResolver == null)
throw new ArgumentException("xamlTypeResolver");
// Use the type resolver to get a Type instance
Type type = xamlTypeResolver.Resolve(typeString);
// Get the member name substring
string fieldString = _member.Substring(dotIndex + 1, _member.Length – dotIndex – 1);
if (fieldString == string.Empty)
throw new ArgumentException("fieldString");
// Use the built-in parser for enum types
if (type.IsEnum)
{
return Enum.Parse(type, fieldString, true);
}
// For other types, reflect
bool found = false;
object value = null;
object fieldOrProp = type.GetField(fieldString, BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Static);
if (fieldOrProp == null)
{
fieldOrProp = type.GetProperty(fieldString, BindingFlags.Public
| BindingFlags.FlattenHierarchy | BindingFlags.Static);
if (fieldOrProp is PropertyInfo)
{
value = ((PropertyInfo)fieldOrProp).GetValue(null, null);
found = true;
}
}
else if (fieldOrProp is FieldInfo)
{
value = ((FieldInfo)fieldOrProp).GetValue(null);
found = true;
}
if (found)
return value;
else
throw new ArgumentException("not found");
}
}
Now all I need to do is add a namespace to my Silverlight view and then use it in XAML as follows:
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="{ext:Static Member=ext:Common.StaticText}" />
</Grid>
That’s it! I will definitely be using this quite often. I would like to mention that unlike in WPF where you don’t have to specify the “Member” property explicitly, in Silveright you have to explicitly set the Member property. This is because there is not a ConstructorArgument attribute in Silverlight. So until then you will need to have a little extra text in your markup syntax.
July 13, 2012 09:45 by
Scott
Silverlight 5 Beta brings the enormously useful ability to set a break point in your Xaml where you have a data binding. This can greatly simplify debugging and fixing binding issues.
To see this, create a new Silverlight 5 project and set up the Xaml to have 5 rows and 2 columns. Place the title in the first row (spanning both columns) and prompts in the next 4 rows. The prompts are
- FullName
- Address
- Phone
- Email
Add four TextBlocks in the second column to display the values that will correspond to these prompts. The Xaml for the four prompts looks like this:
<TextBlock
Grid.Column="1"
Grid.Row="1"
Margin="5"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Text="{Binding FullName}" />
<TextBlock
Grid.Column="1"
Grid.Row="2"
Margin="5"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Text="{Binding Address}" />
<TextBlock
Grid.Column="1"
Grid.Row="3"
Margin="5"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Text="{Binding PhoneNumber}" />
<TextBlock
Grid.Column="1"
Grid.Row="4"
Margin="5"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Text="{Binding Email}" />
To make this work, of course, we need a class and an instance to bind to. Begin by creating a new class, Person,
public class Person
{
public string FullName { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
In MainPage.xaml.cs create an instance of Person, and set that instance to be the data context for the bindings,
public MainPage()
{
InitializeComponent();
var per = new Person()
{
FullName = "Jesse Liberty",
Address = "100 Main Street, Boston, MA",
Email = "[email protected]",
Phone = "617-555-1212"
};
this.DataContext = per;
}
When you run this you’ll find that three of the four bindings work well, but the phone number is not displayed. Set a break point in the Xaml folder on the binding for the PhoneNumber and run the application. When you hit the break point examine the locals window as shown in the illustration to the below.
Note that there is an error message. By clicking on the message you can open a text reader for the entire error message, as shown in the next figure to the below.
The error message indicates that there is no property PhoneNumber in the type Person, and sure enough, a quick check of the code shows that the property is just Phone.
Change the binding from PhoneNumber to Phone and the program works as expected.
June 29, 2012 08:54 by
Scott
In this article, I am going to explain how to design a RichTextBox in Silverlight. This example also demonstrates the RichTextBox control as well. It is easy to formatt a Silverlight RichTextBox at design time through XAML. In this example I have used an image to illustrate the example clearly.
<UserControl x:Class="SilverlightApplication3.MainPage"
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400" DataContext="{Binding}">
<Grid x:Name="LayoutRoot" Background="White" Height="450" Width="550">
<RichTextBox HorizontalAlignment="Left" Margin="10,12,0,0" Name="contentBox" VerticalAlignment="Top" Height="330" Width="390" IsReadOnly="True" Background="#FFFFFF69">
<Paragraph FontFamily="Arial" FontSize="12" TextAlignment="Justify">
This photograph shows a
<Run Text=" blue hills " FontStyle="Italic" FontWeight="ExtraBold" /> belongs to the
<Run Text=" high " Foreground="blue" FontWeight="ExtraBold"/> graphic photography. High graphic photography requires a great deal of precision.
<LineBreak/>
<InlineUIContainer>
<Image Height="143" HorizontalAlignment="Left" Margin="144,82,0,0" Name="images" Stretch="Uniform" VerticalAlignment="Top" Width="196" Source="/SilverlightApplication3;component/Images/Blue%20hills.jpg" />
</InlineUIContainer>
<LineBreak/>
<LineBreak/> |
</Paragraph>
</RichTextBox>
</Grid>
</UserControl>
Now I am going to explain the code so that it can be easily understood. It creates a RichTextBox, with some text and an image. To place and format the text, I first use the Paragraph element, then the Run element. Note that the Paragraph element also has a Foreground property but which I have not used here. In this I use the Run element which is useful to format text. The RichTextBox control also allows you to add elements of type Bold, Underline etc.The Run element derives from the Inline element, an Inline cannot be used directly within a RichTextBox control, however, you can use the Run element.
The LineBreak element is used to introduce line breaks.
The Image is placed inside the InlineUIContainer.
InlineUIContainer: A mandatory child element that is used to place an Image in the RichTextBox control.
You can have as many Paragraph and Run elements as you want, in a RichTextBox control. Using a combination of Paragraph and Run elements, you can format the text in various ways.
The output of the above application is shown below:
June 13, 2012 08:26 by
Scott
One of the new features included with the Silverlight 5 RC is the ability to interact with Platform Invocation Services, or PInvoke for short. This functionality allows managed code, like your Silverlight application, to make calls to unmanaged code like the C++ code that exists in DLLs on your system. PInvoke can be quite complex and covers a lot of different scenarios, so I've focused on a simple scenario to help you get started. You can learn more about PInvoke by reading this MSDN tutorial.
In this post, I will show you how to build a Silverlight Out-of-Browser (OOB) application that uses the native DLLs on your machine to play "beeps." With modern versions of Windows 7, the beeps have evolved into complex sounds that you can assign to various functions. Create a new Silverlight application called "PInvoke," set it to run out of browser and be sure to check the box that indicates it requires elevated trust.
Take a look at the MessageBeep function. It is documented here. The first thing you'll notice is that the type of beep or sound to play is not very friendly as it is passed in as an unsigned integer. Based on the documentation, you can create the following enumeration to simplify things and expose a few key types:
1 public enum BeepTypes : uint
2 {
3 Ok = 0x00000000,
4 Error = 0x00000010,
5 Warning = 0x00000030,
6 Information = 0x00000040
7 }
To make it easy to take a string and cast it to the enumeration value, add this extension method as well:
01 public static class BeepTypeExtensions
02 {
03 public static BeepTypes AsBeepTypeEnum(this string beepType)
04 {
05 BeepTypes beepTypeEnum;
06 return Enum.TryParse(beepType, true, out beepTypeEnum)
07 ? beepTypeEnum
08 : BeepTypes.Error;
09 }
10 }
It is always good practice to encapsulate your calls to unmanaged code in a managed class. This limits the exposure and dependency on PInvoke. It also allows you to write more portable code because you can implement the calls in managed code or simply stub out empty methods for targets that don't support the PInvoke implementation. Here is a simple contract to play a sound:
1 public interface ISoundPlayer
2 {
3 void PlaySound(BeepTypes type);
4 }
Now for the implementation. Create a class called SoundPlayer. The documentation gives you the message signature and the DLL that the method is located in. Bridging to the method in this example is very easy. First, include a using statement for System.Runtime.InteropServices. This is where the PInvoke bridge lives. Next, simply define the message signature as a static extern and import the DLL:
1 [DllImport("User32.dll")]
2 private static extern Boolean MessageBeep(UInt32 beepType);
Implement the contract and call the method you just imported using PInvoke:
1 public void PlaySound(BeepTypes type)
2 {
3 if (!MessageBeep((UInt32) type))
4 {
5 throw new Exception("Beep failed!");
6 }
7 }
That's all there is to it! Now wire up some Xaml in the main page to host four buttons:
01 <Grid x:Name="LayoutRoot" Background="White">
02 <Grid.RowDefinitions>
03 <RowDefinition Height="1*"/>
04 <RowDefinition Height="1*"/>
05 </Grid.RowDefinitions>
06 <Grid.ColumnDefinitions>
07 <ColumnDefinition Width="1*"/>
08 <ColumnDefinition Width="1*"/>
09 </Grid.ColumnDefinitions>
10 <Button x:Name="Ok" Content="OK" Grid.Row="0" Grid.Column="0" Click="Button_Click"/>
11 <Button x:Name="Error" Content="Error" Grid.Row="0" Grid.Column="1" Click="Button_Click"/>
12 <Button x:Name="Warning" Content="Warning" Grid.Row="1" Grid.Column="0" Click="Button_Click"/>
13 <Button x:Name="Information" Content="Information" Grid.Row="1" Grid.Column="1" Click="Button_Click"/>
14 </Grid>
Make sure that the name of the button matches the name of the enum. In the code-behind for the main page, create an instance of the sound player:
1 private readonly ISoundPlayer _soundPlayer = new SoundPlayer();
Now you can implement the button click event. Simply cast the name of the button to the enumeration and call the method on your managed class:
1 private void Button_Click(object sender, RoutedEventArgs e)
2 {
3 var button = sender as Button;
4 if (button == null)
5 {
6 return;
7 }
8 _soundPlayer.PlaySound(button.Name.AsBeepTypeEnum());
9 }
That's it! Run the application in OOB mode and you will be able to press the buttons and hear your default Windows sounds play. If you change your theme or override the sounds, the application will play the correct sounds because it is bridging to the unmanaged code and asking the operating system to play the sound rather than trying to play it from a resource embedded within the Silverlight application.
Hopefully this light example will help you get started. PInvoke has a number of uses from interfacing directly with USB ports to enumerating drives and devices on the host system. It certainly opens the door to a new realm of possibilities with Silverlight.
May 29, 2012 08:43 by
Scott
One of the powerful new features around templating in the Silverlight 5 beta is the ability to produce a DataTemplate that will be implicitly associated with a particular data type.
For example, if I have these 2 simple types Person and Vehicle;
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
public class Vehicle
{
public string Type { get; set; }
public int Wheels { get; set; }
}
then I can define implicit templates for them by writing templates such as these;
<UserControl.Resources>
<DataTemplate
DataType="local:Person">
<StackPanel>
<TextBlock
Text="{Binding FirstName}" />
<TextBlock
Text="{Binding LastName}" />
<TextBlock
Text="{Binding Age}" />
</StackPanel>
</DataTemplate>
<DataTemplate
DataType="local:Vehicle">
<StackPanel>
<TextBlock
Text="{Binding Type}" />
<TextBlock
Text="{Binding Wheels}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
where I have not specified a Key for these resources but have, instead, specified a DataType and that’s enough for Silverlight to figure it out.
If I have a scenario like this one where I have a ListBox bound to a set of Items;
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition
Height="Auto" />
<RowDefinition
Height="Auto" />
</Grid.RowDefinitions>
<ListBox
ItemsSource="{Binding Items}">
</ListBox>
<Button
Command="{Binding AddPerson}"
Content="Add Person"
Grid.Row="1" />
<Button
Command="{Binding AddVehicle}"
Content="Add Vehicle"
Grid.Row="2" />
</Grid>
with a DataContext providing a view model like this one;
public class ViewModel
{
public ViewModel()
{
this.Items = new ObservableCollection<object>();
this.AddPerson = new SimpleCommand(() =>
{
this.Items.Add(
new Person()
{
FirstName = "TestFirst",
LastName = "TestLast",
Age = 22
});
});
this.AddVehicle = new SimpleCommand(() =>
{
this.Items.Add(
new Vehicle()
{
Type = "Car",
Wheels = 4
});
});
}
public ObservableCollection<object> Items { get; set; }
public ICommand AddPerson { get; set; }
public ICommand AddVehicle { get; set; }
}
then whenever I add a Person to the ListBox the runtime will find the right implicit template to display the Person and if I add a Vehicle to the ListBox then the runtime will do the right thing there too;
and, if for example I was to make my ViewModel implement property change notification and then bind up a new property called SelectedItem to my ListBox then I can bring in a ContentPresenter and it will also make use of the implicit template as in;
<UserControl.Resources>
<DataTemplate
DataType="local:Person">
<StackPanel>
<TextBlock
Text="{Binding FirstName}" />
<TextBlock
Text="{Binding LastName}" />
<TextBlock
Text="{Binding Age}" />
</StackPanel>
</DataTemplate>
<DataTemplate
DataType="local:Vehicle">
<StackPanel>
<TextBlock
Text="{Binding Type}" />
<TextBlock
Text="{Binding Wheels}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<UserControl.DataContext>
<local:ViewModel />
</UserControl.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition
Height="Auto" />
<RowDefinition
Height="Auto" />
</Grid.RowDefinitions>
<ListBox
ItemsSource="{Binding Items}"
SelectedValue="{Binding SelectedItem,Mode=TwoWay}" />
<Button
Command="{Binding AddPerson}"
Content="Add Person"
Grid.Row="1" />
<Button
Command="{Binding AddVehicle}"
Content="Add Vehicle"
Grid.Row="2" />
<ContentPresenter
Grid.Column="1"
Content="{Binding SelectedItem}" />
</Grid>
and so then both the ListBox on the left and the ContentPresenter on the right are using implicit templates to display content;
(as an aside, I also tried this with a ContentPresenter inside a Tooltip and it didn’t work for me so far in the beta).
Naturally, you can override these implicit templates so if I want a different template for my ContentPresenter I can simply add an implicit template that is nearer to the ContentPresenter in the hierarchy of resource resolution as in;
<UserControl.Resources>
<DataTemplate
DataType="local:Person">
<StackPanel>
<TextBlock
Text="{Binding FirstName}" />
<TextBlock
Text="{Binding LastName}" />
<TextBlock
Text="{Binding Age}" />
</StackPanel>
</DataTemplate>
<DataTemplate
DataType="local:Vehicle">
<StackPanel>
<TextBlock
Text="{Binding Type}" />
<TextBlock
Text="{Binding Wheels}" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<UserControl.DataContext>
<local:ViewModel />
</UserControl.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition
Height="Auto" />
<RowDefinition
Height="Auto" />
</Grid.RowDefinitions>
<ListBox
ItemsSource="{Binding Items}"
SelectedValue="{Binding SelectedItem,Mode=TwoWay}" />
<Button
Command="{Binding AddPerson}"
Content="Add Person"
Grid.Row="1" />
<Button
Command="{Binding AddVehicle}"
Content="Add Vehicle"
Grid.Row="2" />
<Grid
Grid.Column="1">
<Grid.Resources>
<DataTemplate
DataType="local:Vehicle">
<StackPanel
Orientation="Horizontal">
<TextBlock
Text="{Binding Type}" />
<TextBlock
Text="{Binding Wheels}" />
</StackPanel>
</DataTemplate>
</Grid.Resources>
<ContentPresenter
Grid.Column="1"
Content="{Binding SelectedItem}"/>
</Grid>
</Grid>
and, naturally, you can also mix/match this implicit approach with the explicit approach that you’d use in Silverlight 4 today.
I think this is a pretty powerful addition to the Silverlight 5 binding/templating abilities and it’ll be interesting to see what other folks and frameworks do with it.
May 22, 2012 11:02 by
Scott
May 14, 2012 08:40 by
Scott
This article will explore how to use the ViewBox control in Silverlight 5.
The ViewBox control allows you to place a child control such as Image within it in such a way that it will be scaled appropriately to fit the available without any distortion. It is typically used in 2D graphics.
We will begin with creating a new Silverlight 5 project.
Modify the existing XAML code of MainPage.xaml so that a Grid of 1 column and three rows is created. The code for the same is shown below:
<UserControl x:Class="SilverlightDemo.MainPage"
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006 mc:Ignorable="d" xmlns:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/ sdk HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid x:Name="LayoutRoot" Background="White" Height="300" Width="300">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
</Grid>
</UserControl>
Drag and drop the Viewbox control from the Toolbox into the XAML code between the <Grid></Grid> tags. Specify its row and column in the grid to be 0. The resulting code is seen below.
<UserControl x:Class="SilverlightDemo.MainPage"
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
xmlns:d=http://schemas.microsoft.com/expression/blend/2008
xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006 mc:Ignorable="d" xmlns:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/ sdk HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
</controls:Viewbox>
</Grid>
</UserControl>
Right click on the project name in the Solution Explorer pane and select Add Existing Item option. Choose the image "Winter.jg" from the My Documents\My Pictures\Sample Pictures folder.
Drag and drop an Image control in between the <controls:ViewBox> and </controls:ViewBox> tag and modify its code as shown below, to specify its source and size.
<Grid x:Name="LayoutRoot" Background="White" Height="300" Width="300">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
<Image Source="Winter.jpg" Height="40" Width="40"></Image>
</controls:Viewbox>
</Grid>
Drag and drop another ViewBox and then an Image control in between the second <controls:ViewBox> and </controls:ViewBox> tag.
Modify the XAML as shown below:
<Grid x:Name="LayoutRoot" Background="White" Height="300" Width="300">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<controls:Viewbox Grid.Row="0" Grid.Column="0" Height="120" Width="120">
<Image Source="Winter.jpg" Height="40" Width="40"></Image>
</controls:Viewbox>
<controls:Viewbox Grid.Row="1" Grid.Column="0" Height="70" Width="90">
<Image Source="Winter.jpg" Height="40" Width="40"></Image></controls:Viewbox>
</Grid>
Save the solution, build and execute it. When you see the output, you will observe that the two images show no distortion whatsoever though their height and width are not the same. This has happened because of the ViewBox.
Conclusion : Thus, you learnt how to add and use a ViewBox control in a Silverlight application