European Silverlight 4 & Silverlight 5 Hosting BLOG

BLOG about Silverlight 5 Hosting and Its Techologies - Dedicated to European Windows Hosting Customer

European Silverlight 4 Hosting :: Create Custom Control in Silverlight 4

clock October 20, 2011 06:51 by author Scott

In this tutorial, I will show you how to create custom control in Silverlight. First of all, we need to create a Silverlight project. Assume, you already know about it. Just for your reference, create a new project. From the left panel, select Silverlight and chose "Silverlight Application" from the right panel. Give a proper name for your application and solution. Click ok to continue.

Then, once it is done, you need to created a Custom Control. In this example, we will just create a default control without any additional customization. See this image below



To do this, right click on your Silverlight project, from the context menu select "Add" and from the second level context menu click "New Item". This will open the "Add New Item" dialog box.

As shown in the below screen shot, select "Silverlight Templated Control" and give you proper name to the control. Remember that, the "Silverlight Templated Control" is the template for Custom Silverlight control.



Click "Add" button to add the custom control into your project. Once the control creation is done, you will notice two things in the solution explorer. Expand the "Solution Explorer" and there you will find the following things:

1. A "Themes" folder containing a file called "Generic.xaml". This is the default resource file for all of your styles for your controls.

2. A "MyControl.cs" file, which is nothing but the class of your custom control. The class name is the control name.

Note that, if you create multiple controls the IDE will create multiple class files for you with the name of the control. But the resource file will be same. All styles and templates of your control will go into the same file.



The above screenshot will give you better visibility of the files that has been created in our demo application.

Here we will discuss about the class of the Custom control. You will get detailed knowledge on the class in later part of the series. For now just know, every control by default derives from base class called “Control”. You may change the base class to other control depending upon your requirement.

Have a look into the basic code that has been generated for you by the IDE:

using System.Windows.Controls; 

namespace CustomControlDemo
{
    public class MyControl : Control
    {
        public MyControl()
        {
            this.DefaultStyleKey = typeof(MyControl);
        }
    }
}

You will see the above code in the constructor. It takes the control style from the resource file and set it as the default style of the control. More on the class, we will discuss later.

You will find the basic template of the custom control in the Generic.xaml file. Open the file and you will find the below style inside the ResourceDictionary: 

<Style TargetType="local:MyControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyControl">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
 

The first line describes the TargetType of the style. The second line declares the Template of the control. Third line sets the value of the template. The child of the value is your ControlTemplate. You can design your control template here.

One thing I want to tell you here is that, this is the default template of any control. You can add more style values before starting the template declaration. We will discuss this later.

Let us add the custom control that we created to our main page. To do this, you need to add the XMLNS namespace in the XAML. In our case, it is the project name. Once you declare the namespace, you will be able to access the control easily.

<UserControl x:Class="CustomControlDemo.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
    xmlns:CustomControlDemo="clr-namespace:CustomControlDemo" mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400"> 

    <Grid x:Name="LayoutRoot" Background="White">
        <CustomControlDemo:MyControl
            Width="200"
            Height="200"
            Background="Yellow"
            BorderBrush="Red"
            BorderThickness="1"/>
    </Grid>
</UserControl>
 

The above code will explain you everything. There we added our custom control named "MyControl" with proper declaration of height and width. If you don't specify the height and width, it will take the whole screen of the application (only for our example).

If you run the application, you will not see anything rather than the blank screen. This is because the control has default transparent background. Hence, we added a background color, border brush and border thickness to the control in the above code.



Once you run the application now, you will see the above UI in your browser. The rectangle is the custom control that we created in this sample. If you modify the control template, it will change the UI here automatically.



European Silverlight 4 Hosting :: WCF 4.0 Automatic Formatting with Jquery Ajax

clock October 10, 2011 06:49 by author Scott

at this time I am going to look at Automatic Formatting in WCF 4.0.That is one of the great addition in WCF Web HTTP programming model(WCF RESTful). By using this feature it’s dynamically determine the format for the service operation. Previously, if consumed JSON and XML format for the same operation of the service then must have defined two different operations with explicitly annotated RequestFormat parameter of the WebGetAttribute and WebInvokeAttribute attributes.

For getting json format in WCF 3.5

[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json)]
string GetJsonData();

For getting Xml format in WCF 3.5

[OperationContract]

[WebGet(RequestFormat = WebMessageFormat.Xml)]
string GetXmlData();

Now we have option either go with explicit as above or go with new automatic way .By default Automatic format selection is disable due to backwards compatibility and when it’s enabled, it would automatically get the best format in which to return the response. WCF infrastructure actually checks the type which is contained the request messages of Accept Header. The first priorities for media types, if it’s not found in Accept Header than its checks the content-type of the request message and if content-type would not give the suitable response than it would be used default format setting which is defined by RequestFormat parameter of the WebGetAttribute and WebInvokeAttribute attributes and at the last if there is no any default format setting than it would be used value of the DefaultOutgoingResponseFormat property.

1. Priorities of media types in request message’s Accept Header.
2. The content-type of the request message.
3. The default format setting in the operation.
4. The default format setting in the WebHttpBehavior.

Automatic format selection depends on AutomaticFormatSelectionEnabled property. It can be enabled programmatically or using configuration, for getting the clarification I would like to show example of it with Jquery, using  jquery I will be getting the different  format by calling the same operation of the service, for keeping it simple I am enabling the AutomaticFormatSelectionEnabled through standard endpoints, so let’s start it.

First I am going to create an empty web application JqueryWithWCF and hosting it at IIS.



I am going to add following items in the solution.

- WCFService item named 
RestfulService.svc
-
html page named 
jqueryPage.htm
- jquery scripts
file



We have to add System.ServiceModel.Web
 reference for working with WCF RESTful services.



Now let’s look at the
IRestfulService.cs code

namespace WCFRestfulService
{
    [ServiceContract]
    public interface IrestfulService
    {
        [OperationContract]
        [WebGet(UriTemplate = "/data")]
        string GetData();
    }
}

I added ServiceContract attribute at intrface to expose the service and OperationContract attribute for expose the operation out of the world ,now we have to add WebGet attribute with property name UriTemplate=”/data”, it means, it can be called using UriTemplate property name.

Look at the RestfulService.cs code

namespace WCFRestfulService
{
    public class RestfulService : IrestfulService
    {
        public string GetData()
        {
            return "WCF 4.0 has introduced
            a new property \"automaticFormatSelectionEnabled\"";
        }
    }
}

There is nothing special I did, just implemented IRestfulService interface and return a string.

Here is very key part for enabling the Automatic formate, we have Three different ways to enable the automaticFormatSelectionEnabled ,

1. Using Coding with ServiceHost object we can enable it.
2. Using webhttp behavior option
3. Using the standard endpoints

I am going with standard endpoints, because in standard endpoints we don’t need to configure each and every attribute , it has already configured the some attribute build in , so here is the configuration



As we can see in the above, I have commented behavior and serviceHostEnviroment tag, because we don’t need to service metadata and I have add the standard endpoint with “automaticFormatSelectionEnabled” attribute with value true.

That’s it, we have made a restful service and we can get the JSON or XML format by using single operation.

Now we have to put code at jqueryPage.htm page , here is the code of the page

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        ul{
            border:1px solid black;
            overflow:hidden;
            width:270px;
        }
        li {
            list-style-type:none;
            float:left;
            padding:5px;        
        }
    </style>
    <script src="Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(function () {

            // javascript object for getting all the jquery objects
            var pageElements = {
                actionButton: $('#btnAction'),
                xmlRadio: $('#rdoXml'),
                jsonRadio: $('#rdoJson'),
                xmlLabel: $('#lblGetXml'),
                jsonLabel: $('#lblGetJson'),
                isXML: true,
                dataTypeValue: 'XML'                
            };

            // set the button value on page load
            SetButtonValue(pageElements.xmlRadio, pageElements.xmlLabel,
                           pageElements.actionButton);

            //click event of xml radio button
            pageElements.xmlRadio.bind('click', function () {
                pageElements.isXML = true;
                SetButtonValue(pageElements.xmlRadio, pageElements.xmlLabel,
                           pageElements.actionButton);
            });

            //click event for json radio button
            pageElements.jsonRadio.bind('click', function () {
                pageElements.isXML = false;
                SetButtonValue(pageElements.jsonRadio, pageElements.jsonLabe
,

                           pageElements.actionButton);
            });

            //click event of the action button
            pageElements.actionButton.bind('click', function () {

                if (!pageElements.isXML) {
                    pageElements.dataTypeValue = 'JSON';
                } else {
                    pageElements.dataTypeValue = 'XML';
                }

                //jquery ajax method for getting the result
                $.ajax({
                    type: 'GET',
                    url: '/WCFRestfulService/RestfulService.svc/data',
                    contentType: 'application/json; charset=utf-8',                    
                    dataType: pageElements.dataTypeValue,
                    processdata: true,
                    success: function (msg) {                        
                        AjaxSuccess(msg, pageElements.isXML);
                    },
                    error: function (msg) {
                        alert(msg.error);
                    }
                });
            });
        });

        //it will call when the ajax hit successful
        function AjaxSuccess(result,isXML) {
            if (isXML) {
                alert($(result).find('string').text());
            } else {
                alert(result);
            }
        }

        //set button value on click on radio buttons
        function SetButtonValue(elem,label,button) {
            var buttonAction = $('#btnAction');
            if (elem.is(':checked')) {
                button.val(label.text());
            }
        }
    </script>
</head>
<body>    
    <div>
        <ul>            
            <li>
                <input type="radio" name="rdobutton" id="rdoXml"
                 value="Get XML" checked="checked" /></li>
            <li id="lblGetXml">Get XML</li>

            <li>
                <input type="radio" name="rdobutton" id="rdoJson"
                 value="Get JSON" /></li>
            <li id="lblGetJson">Get JSON</li>
        </ul>
        <input type="button" id="btnAction" value="" />
    </div>
</body>
</html>

I have created two radio buttons and a input button, when we hit the button it will call the jquery ajax method and check the pageElements.isXML Boolean value, if its false than JSON format called otherwise XML. For getting the proof i am using firebug, here is the result of firebug when we check radio button with Get XML and Get JSON.



I hope so you enjoyed the post . J



European Silverlight 4 Hosting :: How to Use "ClickMode" for Button Control in Silverlight?

clock September 29, 2011 08:10 by author Scott

In this article let us see the different ways of using the property ClickMode for a Button Control in a silverlight application. As usual, open the visual studio and select the silverlight project.

First let us drag three different Button and TextBlock controls to Stack Panel as shown below into MainPage.xaml. Here i used a property
called "ClickMode" for all the three button controls, But the value assigned to it is different.

For the first button i assigned the value Hover to the ClickMode property, It means that the
click event handler takes place whenever the mouse is hovered onto this button.

For the
second button i assigned the value Press to the ClickMode property, It means that the click event handler takes place whenever the mouse is clicked on this button.

For the third button i assigned the value Release to the ClickMode property, It means that the click event handler takes place whenever the mouse is released from this button. 

        <Button x:Name="btn1" Margin ="5" HorizontalAlignment="Left"
            Foreground="Black" Width="320" Click="OnClick1"
            Content="On Mouse Hover this text will appear below"
ClickMode
="Hover" />


        <TextBlock x:Name="text1" Margin ="0,8,0,0" />

        <Button x:Name="btn2" Margin ="5,5,5,5"  HorizontalAlignment="Left"             Foreground="Black" Width="320" Click="OnClick2"
            Content="On Button Press this text will appear below" ClickMode="Press" />

        <TextBlock x:Name="text2" Margin="0,8,0,0" />

<Button x:Name="btn3" Margin ="5,5,5,5" HorizontalAlignment="Left" Click="OnClick3" Width="320" Content="On Button Release this text will appear below" ClickMode="Release"/>

        <TextBlock x:Name="text3" Margin ="0,8,0,0" />

Now I am writing the code for button click events in the MainPage.xaml.cs

public
MainPage()
        {
            InitializeComponent();          

        }
        void OnClick1(object sender, RoutedEventArgs e)
        {
            btn1.Foreground = new SolidColorBrush(Colors.Blue);
            text1.Text = "On Mouse Hover this text will appear below.";
            text2.Text = "";
            text3.Text = "";
        }

        void OnClick2(object sender, RoutedEventArgs e)
        {
            btn2.Foreground = new SolidColorBrush(Colors.Green);
            text1.Text = "";
            text2.Text = "On Button Press this text will appear below.";
            text3.Text = "";
        }

        void OnClick3(object sender, RoutedEventArgs e)
        {
            btn1.Foreground = new SolidColorBrush(Colors.Green);
            btn2.Foreground = new SolidColorBrush(Colors.Blue);
            text1.Text = "";
            text2.Text = "";
            text3.Text = "On Button Release this text will appear below.";
        }

Thats it!!! Just press F5 and see the result. 


The output for the first Button looks like as



The output for the second Button looks like as



Note: For the people who find it difficult to integrate the above
code, I am pasting the complete code here.

MainPage.Xaml:

<UserControl x:Class="SilverlightTest1.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
   xmlns:sdk=http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <StackPanel x:Name="LayoutRoot" Background="White" Margin="10">

        <Button x:Name="btn1" Margin ="5" HorizontalAlignment="Left"
            Foreground="Black" Width="320" Click="OnClick1"
            Content="On Mouse Hover this text will appear below" ClickMode="Hover" />

        <TextBlock x:Name="text1" Margin ="0,8,0,0" />

        <Button x:Name="btn2" Margin ="5,5,5,5"  HorizontalAlignment="Left"
            Foreground="Black" Width="320" Click="OnClick2"
            Content="On Button Press this text will appear below" ClickMode="Press" />

        <TextBlock x:Name="text2" Margin="0,8,0,0" />

<Button x:Name="btn3" Margin ="5,5,5,5" HorizontalAlignment="Left" Click="OnClick3" Width="320" Content="On Button Release this text will appear below" ClickMode="Release"/>

        <TextBlock x:Name="text3" Margin ="0,8,0,0" />

    StackPanel>

UserControl>

MainPage.Xaml.cs:

public MainPage()
        {
            InitializeComponent();           

        }
        void OnClick1(object sender, RoutedEventArgs e)
        {
            btn1.Foreground = new SolidColorBrush(Colors.Blue);
            text1.Text = "On Mouse Hover this text will appear below.";
            text2.Text = "";
            text3.Text = "";
        }

        void OnClick2(object sender, RoutedEventArgs e)
        {
            btn2.Foreground = new SolidColorBrush(Colors.Green);
            text1.Text = "";
            text2.Text = "On Button Press this text will appear below.";
            text3.Text = "";

        }

        void OnClick3(object sender, RoutedEventArgs e)
        {
            btn1.Foreground = new SolidColorBrush(Colors.Green);
            btn2.Foreground = new SolidColorBrush(Colors.Blue);
            text1.Text = "";
            text2.Text = "";
            text3.Text = "On Button Release this text will appear below.";
        }

Happy coding



European WCF Hosting :: Use dataset across WCF service

clock September 16, 2011 06:50 by author Scott

Some times you need to return a set of data from a WCF service and When you are working with ado.net, dataset is the obvious reason you wish at your client side. But passing dataset can make service less interoportable because in that case you are forced to use dataset on your client code. Second point is that dataset might become very bulky as per size of the data grows. Instead, passing dataset we can pass compressed byte array of dataset from WCF service and consume it like a byte array on client end. After Uncompression, either you can convert it into dataset or you can use this XML in any other form you want.

For this, lets first create a WCF service:

[OperationContract]
public byte[] GetEmployee(string BranchId)
{
string sQ = "Select EmpId, EmployeeName from EmployeeMaster";

SqlConnection objConn = new SqlConnection("Data Source=[YourServer];Initial Catalog=[Database];User ID=[UserName];Password=[Password];MultipleActiveResultSets=True");
SqlCommand objCom = new SqlCommand(sQ, objConn);
SqlDataAdapter objDa = new SqlDataAdapter(objCom);
DataSet objDs = new DataSet();
objDa.Fill(objDs);
//Now we'll convert dataset into byte array and compress it using gzStream.
byte[] binaryDataResult = null;
MemoryStream memStream = new MemoryStream();
GZipStream gzStream = new GZipStream(memStream, CompressionMode.Compress);
objDs.WriteXml(gzStream);
binaryDataResult = memStream.ToArray();
gzStream.Close();
memStream.Close();
return binaryDataResult;
}

Here, We are first filling dataset from database then after compression using GZipStream, we are converting it to byte array. At client end we will get this byte array and we'll again follow these steps in reverse order.

ServiceClient s = new ServiceClient();
byte[] btEmployee = (byte[])s.GetEmployee("0");
if (btEmployee != null)
{
MemoryStream mEmployee = new MemoryStream(btEmployee);
GZipStream gStreamEmployee = new GZipStream(mEmployee, CompressionMode.Decompress);
DataSet objDsEmployee = new DataSet();
objDsEmployee.ReadXml(gStreamEmployee);
gStreamEmployee.Close();
gvEmployee.DataSource = objDsEmployee;
gvEmployee.DataBind();
}



European Silverlight 4 Hosting :: Tutorial - How to Send Email in Silverlight

clock August 25, 2011 07:07 by author Scott

In this tutorial I will show you how to send email with Silverlight using .NET framework.

1. Create Silverlight Application Using VS 2010



Above GUI xaml like following,



2. Add asp.net Generic Handler in Web.Project



3. Add Static Class and Create Send Email Function.



4. Add code to perform mail sending through the generic handler.



5. Add This Code At SilverLight Project(MainPage.xaml.cs) on send button click.



6. Then, configure the SMTP settign inside the configuration file, here is settings details.



7. Press F5 and run.

Hope it is help!!



European Silverlight 4 Hosting :: How to Edit Silverlight Page Data Using Domain Service

clock July 21, 2011 05:33 by author Scott

This post requires to create a Silverlight Business Application in Visual Studio 2010.

1. Open the Mainpage.xaml , Add the following XAML code to see the Save changes and Reject changes button

   1: <Button Content="Save Changes" Click="SaveButton_Click"
         Margin="5" 
   2:        x:Name="SaveButton"></Button>
   3: <Button Content="Reject Changes" Click="RejectButton_Click"
               Margin="5"
   4:         x:Name="RejectButton"></Button>
   5: <TextBlock x:Name="ChangeText" VerticalAlignment="Center"
      Width="Auto"></TextBlock>

2. Add the code for button click event handlers as shown below

   1: private void SaveButton_Click(object sender, RoutedEventArgs e)
   2:  {
   3:   awDept.SubmitChanges(OnSubmitCompleted, null);
   4:  }
   5: 
   6:  private void RejectButton_Click(object sender, RoutedEventArgs e)
   7:  {
   8:    awDept.RejectChanges();
   9:    CheckChanges();
  10:  }
  11: private void CheckChanges()
  12:  {
  13:   EntityChangeSet changeSet = awDept.EntityContainer.GetChanges();
  14:   ChangeText.Text = changeSet.ToString();
  15:   bool hasChanges = awDept.HasChanges;
  16:   SaveButton.IsEnabled = hasChanges;
  17:   RejectButton.IsEnabled = hasChanges;
  18:  }
  19: 
  20: private void OnSubmitCompleted(SubmitOperation so)
  21:  {
  22:    if (so.HasError)
  23:     {
  24:         MessageBox.Show(string.Format("Submit Failed: {0}", so.Error.Message));
  25:         so.MarkErrorAsHandled();
  26:      }
  27:             CheckChanges();
  28:  }

  29: private void departmentDataGrid_RowEditEnded(object sender,
          DataGridRowEditEndedEventArgs e)
  30: {
  31:          CheckChanges();
  32: }

3. Open the Metadata file in server project and add the editable attribute to the Id and modified date as shown below

   1: internal sealed class DepartmentMetadata
   2:         {
   3: 
   4:             // Metadata classes are not meant to be instantiated.
   5:             private DepartmentMetadata()
   6:             {
   7:             }
   8: 
   9:             [Editable(false)]
  10:             public short DepartmentID { get; set; }
  11: 
  12:             public string GroupName { get; set; }
  13:             [Editable(false)]
  14:             public DateTime ModifiedDate { get; set; }
  15: 
  16:             public string Name { get; set; }
  17:         }

4. When you run the application you should be able to see the below screen



European Silverlight 4 Hosting :: Binding to a ComboBox in Silverlight

clock May 11, 2011 06:26 by author Scott

Binding to a Combobox

Before we can get to the “gotcha” I came across, we first need to set up how to use binding with a Combobox.  For my example we will be using a simplistic MVVM architecture because it helps to demonstrate the point a bit better.  Just as a reminder, you don’t have to use binding with the Combobox or to recreate the issue described in this post.

So let’s get started with our view model.  For our purposes, the view can be rather simplistic, needing only 2 properties.  I added a method to populate our list data just for completion.

    public class MainPageViewModel : INotifyPropertyChanged
    {
        private string _favoriteConf;

        public MainPageViewModel()
        {
            PopulateConfs();
        }

        public string FavoriteConf
        {
            get { return _favoriteConf; }
            set
            {
                _favoriteConf = value;
                NotifyPropertyChanged("FavoriteConf");
            }
        }

        private List<string> _confs;

        public List<string> Confs
        {
            get { return _confs;  }
            set
            {
                _confs = value;
                NotifyPropertyChanged("Confs");
            }
        }
        private void PopulateConfs()
        {
            Confs = new List<string>()
                {"MIX", "TechEd", "PDC", "DevConnections"};
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        protected  void NotifyPropertyChanged(string propertyName)
        {
            if(PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion
    }

As you can see, we have just the two properties : FavoriteConf and Confs.  Our constructor calls the PopulateConfs to add some data for us to work with.  (Yes, Conf = Conference, I just didn’t want to write out Conference too many times. ).

Now that we have our view model, the next step would be to create our XAML.  For this demonstration, we are going to show two elements: a Combobox and a TextBox.  The Combobox will have our list of conferences (bound to the Confs property) and the TextBox will show the selected conference by binding to the the FavoriteConf property.

If you look at the Combobox, you will notice two different binding statements.  The first one is the ItemsSource is bound to the Confs property.  This is done with the default OneWay binding, since our Combobox will never be modifying the list of data.  The second is the SelectedValue with is bound to the FavoriteConf property.  Since we want to update the FavoriteConf value in our view mode when the user selects a drop down, then we do a two-way binding.

Here is our XAML:

<UserControl x:Class="ComboBoxBinding.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
    xmlns:local="clr-namespace:ComboBoxBinding"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <local:MainPageViewModel x:Key="viewModel"/>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White"
          DataContext="{StaticResource viewModel}">
        <Grid HorizontalAlignment="Center" VerticalAlignment="Center"
              Background="LightGray"
              Height="Auto" Width="Auto">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="150"/>
                <ColumnDefinition Width="150"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="25"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <TextBlock HorizontalAlignment="Center"
                       Text="Select Favorite Conference"/>
            <TextBlock Text="Choose One :" Grid.Row="1"/>
            <ComboBox Grid.Row="1" Grid.Column="1"
                      SelectedValue="{Binding FavoriteConf, Mode=TwoWay}"
                      ItemsSource="{Binding Confs}"/>
            <TextBlock Text="You Picked :" Grid.Row="2"/>
            <TextBox Text="{Binding FavoriteConf}" Grid.Row="2"
                     Grid.Column="1"/>
        </Grid>
    </Grid>
</UserControl>

Note: Since this is a demonstration, I’m creating a static copy of our view model in the resources of our XAML and binding the LayoutRoot’s DataContext to this resource.

If you run the project the application should look something like this:



When you select an item from the Combobox, the TextBox will update with the selected value of the Combobox.



Great! It works, everything is add it should be, right?

Note: Silverlight 4 added some additional properties to the Combobox to make binding easier.  You can read a walkthru of using them on John Papa’s blog
here.

Ordering of XAML Properties : The Gotcha

So let’s take our example one step further, but setting a default value for our FavoriteConf value.  To do this, we are going to change up our constructor to our view model by adding another line of code:

        public MainPageViewModel()
        {
            PopulateConfs();
            FavoriteConf = "MIX";
        }

If we run our example again, this is what we get:



Not exactly what I was looking for.  The TextBox picked up the default value of the FavoriteConf, but why didn’t the Combobox?  Well it turns out, after much head scratching, that the answer is in our XAML.

Let’s take a look at the XAML of our Combobox again:

            <ComboBox Grid.Row="1" Grid.Column="1"
                      SelectedValue="{Binding FavoriteConf, Mode=TwoWay}"
                      ItemsSource="{Binding Confs}"/>

Do you see where we went wrong?

It looked right to me for a while.  However, it turns out that ordering of the properties in XAML can affect the behavior of the control.  If we switch the order of the ItemsSource and the SelectedValue, your XAML will now look something like this:

            <ComboBox Grid.Row="1" Grid.Column="1"
                      ItemsSource="{Binding Confs}"
                      SelectedValue="{Binding FavoriteConf, Mode=TwoWay}"/>

Now, if we run the two examples side-by-side, we get the following:



It turns out that ordering in your XAML can be important and something to look out for if you are not getting the results that you are looking for. If you have found yourself in a similar situation, hopefully this will post will help.



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.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in