Tag Archives: XAML

wCF RIA Service to return simple types except IQuerable

WCF RIA Domain service will always return the IQuerable tyoe not the primitive types like int, or List. In some cases it is eminent that we need to just return the ID field which is int or List<string> customerList to the client not the whole table. The below sample will explain how to do it.

 

Step 1: Create the domain service by right click on the web project of the RIA Service and select New Item and select the Domain Service from the List

image

 

Step 2: Name the domain service to relevant table name in my case “CustomerService.cs”. Click on Add and the list of Tables will be displayed. Select the Customer Table. If you check Enable Editing then Insert and update methods are added to the service. Click Ok to generate the class.

image

 

Step 3: The CustomerService with the below code will be added.

[EnableClientAccess()]
   public class CustomerService : LinqToEntitiesDomainService<AdventureWorksLTEntities>
   {

       // TODO:
       // Consider constraining the results of your query method.  If you need additional input you can
       // add parameters to this method or create additional query methods with different names.
       // To support paging you will need to add ordering to the ‘Customers’ query.
       public IQueryable<Customer> GetCustomers()
       {
           return this.ObjectContext.Customers;
       }

       public void InsertCustomer(Customer customer)
       {
           if ((customer.EntityState != EntityState.Detached))
           {
               this.ObjectContext.ObjectStateManager.ChangeObjectState(customer, EntityState.Added);
           }
           else
           {
               this.ObjectContext.Customers.AddObject(customer);
           }
       }

       public void UpdateCustomer(Customer currentCustomer)
       {
           this.ObjectContext.Customers.AttachAsModified(currentCustomer, this.ChangeSet.GetOriginal(currentCustomer));
       }

       public void DeleteCustomer(Customer customer)
       {
           if ((customer.EntityState != EntityState.Detached))
           {
               this.ObjectContext.ObjectStateManager.ChangeObjectState(customer, EntityState.Deleted);
           }
           else
           {
               this.ObjectContext.Customers.Attach(customer);
               this.ObjectContext.Customers.DeleteObject(customer);
           }
       }
   }                      

 

Step 4: Now add the new method which adds the primitive type.

The first method will return the string and the second method will return List of string.

[Invoke]
       public string GetCustomerEmailId(int customerId)
       {
           var sal = from c in this.ObjectContext.Customers where c.CustomerID == customerId select c.EmailAddress;
           return sal.FirstOrDefault().ToString();
       }

       [Invoke]
       public List<string> GetEmailList(string customerName)
       {
           var salList = from c in this.ObjectContext.Customers where c.FirstName.StartsWith(customerName) select c.EmailAddress;
           return salList.ToList();
       }

Step 5: Build the solution to create a proxy file for the client. Now navigate to the silverlight project and add the below code for calling the service. Basically in the below code i have declared 2 property EmailId and EmailList. Inherited the MainPage from INotifyPropertyChanged to trigger the property change for Xaml to update. Then called the webservice and set these property.

 

using Projectname.Web.Services;
using System.ServiceModel.DomainServices.Client;

public partial class MainPage : Page, INotifyPropertyChanged
    {
        private string _email = string.Empty;
        private List<string> _emailList = null;
        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public MainPage()
        {
            InitializeComponent();
            this.DataContext = this;
            MyCustomerContext ctx = new CustomerContext();
            ctx.GetCustomerEmailId(2, EmailIdCompleted,null);
        }

        public string EmailID
        {
            get
            {
                return _email;
            }
            set
            {
                _email = value;
                this.RaisePropertyChanged("EmailID");
            }
        }

        public List<string> EmailList
        {
            get
            {
                return _emailList;
            }
            set
            {
                _emailList = value;
                this.RaisePropertyChanged("EmailList");
            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void exitApp_Click(object sender, RoutedEventArgs e)
        {
            try
            {
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void GetEmailsButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                CustomerContext ctx = new CustomerContext();
                ctx.GetEmailList(NameTextBox.Text, EmailListCompleted, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void EmailListCompleted(InvokeOperation<IEnumerable<string>> args)
        {
            this.EmailList = args.Value.ToList();
        }

        private void EmailIdCompleted(InvokeOperation<string> args)
        {
            this.EmailID = args.Value.ToString();
        }
    }

Step 6: Add the same to the XAML for the Binding

 

<navigation:Page
           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:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           d:DesignWidth="1024" d:DesignHeight="768"
           Title="CustomerByDate Page" xmlns:riaControls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.DomainServices" xmlns:my="clr-namespace:BusinessApplication2.Web.Models" xmlns:my1="clr-namespace:BusinessApplication2.Web.Services" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit">
    <Grid x:Name="LayoutRoot">
        <StackPanel>
            <Border BorderBrush="Gray" Margin="2,2,2,2" BorderThickness="2,2,2,2" Background="Black" HorizontalAlignment="Stretch" Height="40">
                <TextBlock Text="Sample using simple data type value return on RIA Service" FontSize="20" Foreground="White" />
            </Border>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center">
                <TextBlock VerticalAlignment="Center" Text="Enter name to search:" Margin="5,0,5,0" />
                <TextBox Text="{Binding Path=CustomerName}" Margin="5,0,5,0" Width="163" Name="NameTextBox"/>
                <Button Margin="5,0,5,0" Name="GetEmailsButton" Click="GetEmailsButton_Click" Width="111" Height="30" Content="Get Emails"/>
                <ComboBox Name="CustomerList" ItemsSource="{Binding EmailList}" Width="247" Height="25" Margin="2,0,5,0"/>
                <TextBlock VerticalAlignment="Center" Text="Email Address = " Margin="5,0,5,0" />
                <TextBox Text="{Binding Path=EmailID}" Margin="5,0,5,0" Width="163"/>
            </StackPanel>
        </StackPanel>
    </Grid>
</navigation:Page>

 

Below is the Executed code.

 

image

Calling WCF RIA Service from Code behind

Assume that there is a RIA Service usually under ProjectName.Web and inside the Service folder with the file name ArtifactService.cs and with the below implementation

 

namespace ProjectName.Web.Services
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Data;
    using System.Linq;
    using System.ServiceModel.DomainServices.EntityFramework;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server;
    using ProjectName.Web.Models;

    [EnableClientAccess()]
    public class ArtifactService : LinqToEntitiesDomainService<PROJEntities>
    {

        public IQueryable<Artifact> GetArtifacts()
        {
            return this.ObjectContext.Artifacts;
        }

        public IQueryable<Artifact> GetArtifactById(string projectId)
        {
            if (!string.IsNullOrEmpty(projectId))
            {
                Guid filterValue = Guid.Parse(projectId);
                return this.ObjectContext.Artifacts.Where(i => i.ProjectId == filterValue);
            }
            else
            {
                return null;
            }
        }
        public void InsertArtifact(Artifact artifact)
        {
            if ((artifact.EntityState != EntityState.Detached))
            {
                this.ObjectContext.ObjectStateManager.ChangeObjectState(artifact, EntityState.Added);
            }
            else
            {
                this.ObjectContext.Artifacts.AddObject(artifact);
            }
        }

        public void UpdateArtifact(Artifact currentArtifact)
        {
            this.ObjectContext.Artifacts.AttachAsModified(currentArtifact, this.ChangeSet.GetOriginal(currentArtifact));
        }

        public void DeleteArtifact(Artifact artifact)
        {
            if ((artifact.EntityState != EntityState.Detached))
            {
                this.ObjectContext.ObjectStateManager.ChangeObjectState(artifact, EntityState.Deleted);
            }
            else
            {
                this.ObjectContext.Artifacts.Attach(artifact);
                this.ObjectContext.Artifacts.DeleteObject(artifact);
            }
        }
    }
}

 

In the MainPage.cs we can execute the service with the below way

 

using ProjectName.Web.Services;
using ProjectName.Web.Models;
using System.ServiceModel.DomainServices.Client;

public partial class MainPage : UserControl
    {
public MainPage()
        {
            InitializeComponent();
ArtifactContext raCtx = new ArtifactContext();
                        raCtx.Load(raCtx.GetArtifactByIdQuery("id parameter"), new Action<LoadOperation<Artifact>>(ArtifactLoaded), false);
                        raCtx = null;
         }
        
private void ArtifactLoaded(LoadOperation<Artifact> args)
         {
             datagridData.AutoGenerateColumns = true;
             datagridData.ItemsSource = args.Entities;
             if (args.Entities.Count() > 0)
             {
                 datagridData.SelectedIndex = 0;
             }
             else
             {
                 datagridData.ItemsSource = null;
             }
        }
    }

Datagrid cell coloring and Header Style Wrapping using XAML

Sometime there is a need to change the Datagrid header text to wrap and change the width and the style. The below sample will discuss about the coloring and changing the header style

 

The full source is available here in the SkyDrive

 

Preview of the code

image

 

XAML:

First the Styles needed for the Cell

 

<Style x:Key="dataGridHeaderStyle" TargetType="dataprimitives:DataGridColumnHeader">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" TextWrapping="Wrap" TextAlignment="Center" />
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="RAGCellBorderStyle" TargetType="Border">
            <Setter Property="HorizontalAlignment" Value="Stretch" />
            <Setter Property="VerticalAlignment" Value="Stretch" />
            <Setter Property="BorderThickness" Value="1,1,1,1"/>
            <Setter Property="BorderBrush" Value="Black"/>
        </Style>
        <Style x:Key="RAGCellLabelStyle" TargetType="sdk:Label">
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
            <Setter Property="FontWeight" Value="Bold" />
        </Style>

 

Then apply the style to the DataGrid.

 

<sdk:DataGrid  MinHeight="200" VerticalAlignment="Stretch" AutoGenerateColumns="False" ItemsSource="{Binding}" Name="rAGDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Margin="2,0,2,5">
    <sdk:DataGrid.Columns>
        <sdk:DataGridTemplateColumn x:Name="empricalTypeColumn" Header="Emprical Type" Width="80">
            <sdk:DataGridTemplateColumn.HeaderStyle>
                <Style TargetType="dataprimitives:DataGridColumnHeader">
                    <Setter Property="ContentTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <TextBlock Text="{Binding}" TextWrapping="Wrap" TextAlignment="Center" />
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </sdk:DataGridTemplateColumn.HeaderStyle>
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <sdk:DatePicker SelectedDate="{Binding Path=EmpricalType, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Background="DodgerBlue" Style="{StaticResource RAGCellBorderStyle}" >
                        <sdk:Label Content="{Binding Path=EmpricalType, StringFormat=\{0:d\}}" Style="{StaticResource RAGCellLabelStyle}"  />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Resourcing" Width="82" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Resourcing, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Resourcing, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Resourcing, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>

        <sdk:DataGridTemplateColumn Header="Approval" Width="70" HeaderStyle="{StaticResource dataGridHeaderStyle}" >
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Approval, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Approval, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Approval, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>

        <sdk:DataGridTemplateColumn Header="Project Plan" Width="60" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=ProjectPlan, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=ProjectPlan, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=ProjectPlan, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>

        <sdk:DataGridTemplateColumn Header="Milestone" Width="74" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Milestone, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Milestone, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Milestone, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Financial" Width="70" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Financial, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Financial, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Financial, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Business Case" Width="70" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Business, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Business, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Business, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Risks" Width="50" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Risks, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Risks, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Risks, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Methodology" Width="90" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Methodology, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Methodology, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Methodology, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Supply Service" Width="65" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=SupplyService, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=SupplyService, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=SupplyService, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn Header="Sponsor" Width="67" HeaderStyle="{StaticResource dataGridHeaderStyle}">
            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding Path=Sponsor, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellEditingTemplate>
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Sponsor, Converter={StaticResource colorConvert}}" >
                        <sdk:Label Content="{Binding Path=Sponsor, Mode= OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                    </Border>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
       
    </sdk:DataGrid.Columns>
    <sdk:DataGrid.RowHeight>35</sdk:DataGrid.RowHeight>
</sdk:DataGrid>

 

Converter class

 

public class StatusColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                return new SolidColorBrush(Colors.Gray);
            }
            double? health = (double?)value;

            Brush retColor = Utility.GetHealthColor(health);
            return retColor;

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

 

Supporting Class for converter

public static class Utility
    {
        public static Brush GetHealthColor(double? health)
        {
            Brush retColor;
            if (health == 4)
            {
                retColor = new SolidColorBrush(Colors.Blue);
            }
            else if (health <= 1.99 && health >= 0)
            {
                retColor = new SolidColorBrush(Colors.Red);
            }
            else if (health > 1.99 && health <= 2.99)
            {
                retColor = new SolidColorBrush(Colors.Orange);
            }
            else if (health > 2.99 && health <= 3.99)
            {
                retColor = new SolidColorBrush(Colors.Green);
            }
            else
            {
                retColor = new SolidColorBrush(Colors.Gray);
            }
            return retColor;
        }
    }

 

Datasource

 

public class RAG
    {

        public RAG(Int32 ragId, DateTime empType,double res,double app,double prjPlan, double mile,double fin,double business
            , double risks, double method, double supply,double sponsor)
        {
            this.RAGID = ragId;
            this.EmpricalType = empType;
            this.Resourcing = res;
            this.Approval = app;
            this.ProjectPlan = prjPlan;
            this.Milestone = mile;
            this.Financial = fin;
            this.Business = business;
            this.Risks = risks;
            this.Methodology = method;
            this.SupplyService = supply;
            this.Sponsor = sponsor;
        }

        #region Primitive Properties

        public global::System.Int32 RAGID
        {
            get
            {
                return _RAGID;
            }
            set
            {
                if (_RAGID != value)
                {
                    _RAGID = value;
                }
            }
        }
        private global::System.Int32 _RAGID;
     
        public global::System.DateTime EmpricalType
        {
            get
            {
                return _EmpricalType;
            }
            set
            {
                _EmpricalType = value;
            }
        }
        private global::System.DateTime _EmpricalType;
      
        public global::System.Double Resourcing
        {
            get
            {
                return _Resourcing;
            }
            set
            {
                _Resourcing = value;
            }
        }
        private global::System.Double _Resourcing;
    
        public global::System.Double Approval
        {
            get
            {
                return _Approval;
            }
            set
            {
                _Approval = value;
            }
        }
        private global::System.Double _Approval;

        
        public global::System.Double ProjectPlan
        {
            get
            {
                return _ProjectPlan;
            }
            set
            {
                _ProjectPlan = value;
            }
        }
        private global::System.Double _ProjectPlan;

      
        public global::System.Double Milestone
        {
            get
            {
                return _Milestone;
            }
            set
            {
                _Milestone = value;
            }
        }
        private global::System.Double _Milestone;

         
        public global::System.Double Financial
        {
            get
            {
                return _Financial;
            }
            set
            {
                _Financial = value;
            }
        }
        private global::System.Double _Financial;

        
        public global::System.Double Business
        {
            get
            {
                return _Business;
            }
            set
            {
                _Business = value;
            }
        }
        private global::System.Double _Business;

        public global::System.Double Risks
        {
            get
            {
                return _Risks;
            }
            set
            {
                _Risks = value;
            }
        }
        private global::System.Double _Risks;
          
        public global::System.Double Methodology
        {
            get
            {
                return _Methodology;
            }
            set
            {
                _Methodology = value;
            }
        }
        private global::System.Double _Methodology;

        public global::System.Double SupplyService
        {
            get
            {
                return _SupplyService;
            }
            set
            {
                _SupplyService = value;
            }
        }
        private global::System.Double _SupplyService;

        public global::System.Double Sponsor
        {
            get
            {
                return _Sponsor;
            }
            set
            {
                _Sponsor = value;
            }
        }
        private global::System.Double _Sponsor;

        #endregion
    }

 

Collection Class

 

public class RAGCollection : ObservableCollection<RAG>
    {
        public RAGCollection()
            : base()
        {
            Add(new RAG(1,DateTime.Now,1.2,2.1,3.1,4.0,1,5,2.5,3.5,1.5,5));
            Add(new RAG(2, DateTime.Now.AddDays(2), 2.2, 1.1, 1.1, 3.0, 2, 4, 1.5, 2.5, 3.5, 2.5));
            Add(new RAG(3, DateTime.Now.AddMonths(-10), 1.2, 2.1, 3.1, 4.0, 1, 5, 2.5, 3.5, 1.5, 5));
            Add(new RAG(4, DateTime.Now.AddDays(-20), 1.2, 2.1, 3.1, 4.0, 1, 5, 2.5, 3.5, 1.5, 5));
        }
    }

 

The Full XAML with style and the converter and the header changes

<UserControl x:Class="Forum_2011.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:local="clr-namespace:Forum_2011.Converter"
             xmlns:dataprimitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="1024" d:DesignWidth="768" xmlns:my="clr-namespace:Forum_2011.DataSource" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" Loaded="UserControl_Loaded">
    <UserControl.Resources>
        <CollectionViewSource x:Key="rAGViewSource" d:DesignSource="{d:DesignInstance my:RAG, CreateList=True}" />
        <local:StatusColorConverter x:Key="colorConvert"/>
        <Style x:Key="dataGridHeaderStyle" TargetType="dataprimitives:DataGridColumnHeader">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" TextWrapping="Wrap" TextAlignment="Center" />
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="RAGCellBorderStyle" TargetType="Border">
            <Setter Property="HorizontalAlignment" Value="Stretch" />
            <Setter Property="VerticalAlignment" Value="Stretch" />
            <Setter Property="BorderThickness" Value="1,1,1,1"/>
            <Setter Property="BorderBrush" Value="Black"/>
        </Style>
        <Style x:Key="RAGCellLabelStyle" TargetType="sdk:Label">
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
            <Setter Property="FontWeight" Value="Bold" />
        </Style>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel DataContext="{StaticResource rAGViewSource}">
            <Border BorderBrush="Gray" BorderThickness="2,2,2,2" Background="Black" Height="40" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                <TextBlock Text="Red Amber Green (RAG)" Foreground="White" FontSize="20"/>
            </Border>
            <sdk:DataGrid  MinHeight="200" VerticalAlignment="Stretch" AutoGenerateColumns="False" ItemsSource="{Binding}" Name="rAGDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Margin="2,0,2,5">
                <sdk:DataGrid.Columns>
                    <sdk:DataGridTemplateColumn x:Name="empricalTypeColumn" Header="Emprical Type" Width="80">
                        <sdk:DataGridTemplateColumn.HeaderStyle>
                            <Style TargetType="dataprimitives:DataGridColumnHeader">
                                <Setter Property="ContentTemplate">
                                    <Setter.Value>
                                        <DataTemplate>
                                            <TextBlock Text="{Binding}" TextWrapping="Wrap" TextAlignment="Center" />
                                        </DataTemplate>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </sdk:DataGridTemplateColumn.HeaderStyle>
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <sdk:DatePicker SelectedDate="{Binding Path=EmpricalType, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Background="DodgerBlue" Style="{StaticResource RAGCellBorderStyle}" >
                                    <sdk:Label Content="{Binding Path=EmpricalType, StringFormat=\{0:d\}}" Style="{StaticResource RAGCellLabelStyle}"  />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Resourcing" Width="82" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Resourcing, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Resourcing, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Resourcing, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>

                    <sdk:DataGridTemplateColumn Header="Approval" Width="70" HeaderStyle="{StaticResource dataGridHeaderStyle}" >
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Approval, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Approval, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Approval, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>

                    <sdk:DataGridTemplateColumn Header="Project Plan" Width="60" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=ProjectPlan, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=ProjectPlan, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=ProjectPlan, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>

                    <sdk:DataGridTemplateColumn Header="Milestone" Width="74" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Milestone, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Milestone, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Milestone, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Financial" Width="70" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Financial, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Financial, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Financial, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Business Case" Width="70" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Business, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Business, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Business, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Risks" Width="50" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Risks, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Risks, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Risks, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Methodology" Width="90" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Methodology, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Methodology, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Methodology, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Supply Service" Width="65" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=SupplyService, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=SupplyService, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=SupplyService, Mode=OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                    <sdk:DataGridTemplateColumn Header="Sponsor" Width="67" HeaderStyle="{StaticResource dataGridHeaderStyle}">
                        <sdk:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=Sponsor, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" />
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Border Style="{StaticResource RAGCellBorderStyle}" Background="{Binding Path=Sponsor, Converter={StaticResource colorConvert}}" >
                                    <sdk:Label Content="{Binding Path=Sponsor, Mode= OneWay, StringFormat=0.0}" Style="{StaticResource RAGCellLabelStyle}" />
                                </Border>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                   
                </sdk:DataGrid.Columns>
                <sdk:DataGrid.RowHeight>35</sdk:DataGrid.RowHeight>
            </sdk:DataGrid>
        </StackPanel>
    </Grid>
   
</UserControl>

 

The Code behind for the mainpage.cs

public partial class MainPage : UserControl
    {
        private DataSource.RAGCollection ragColData;
        public MainPage()
        {
            InitializeComponent();
            ragColData = new DataSource.RAGCollection();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

            // Do not load your data at design time.
             if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
             {
                 //Load your data here and assign the result to the CollectionViewSource.
                 System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["rAGViewSource"];
                myCollectionViewSource.Source = ragColData;
             }
        }
    }

 

 

 

Colour converter based on Status string.

Declare a class and inherit from the IValueConverter
using System; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Windows.Ink; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 
using System.Windows.Data;

public class StatusColorConverter:IValueConverter 
    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
        { 
            string status = (string)value; 
            if (value == null) 
            { 
                return new SolidColorBrush(Colors.LightGray); 
            } 
            if (string.IsNullOrEmpty(status)) 
            { 
                return new SolidColorBrush(Colors.LightGray); 
            } 
            else if (status.Trim() == "Open") 
            { 
                return new SolidColorBrush(Colors.Orange); 
            } 
            else if (status.Trim() == "Closed") 
            { 
                return new SolidColorBrush(Colors.Green); 
            } 
            else 
            { 
                return new SolidColorBrush(Colors.LightGray); 
            } 
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
        { 
            throw new NotImplementedException(); 
        } 
    }
Using it in XAML, Below are just the main elements for the understanding. The original XAML page will have more declaration
<navigation:Page xmlns:local="clr-namespace:ProjectName.Converters"
           Title="Page Title Here">
    <navigation:Page.Resources>
        <local:StatusColorConverter x:Key="statusColor" />
    </navigation:Page.Resources>
</navigation:Page>
<Grid>
<Border BorderBrush="White" BorderThickness="2" Background="{Binding Path=Status,Converter={StaticResource colorConvert}}" 
CornerRadius="10,10,10,10" Width="200" Height="150">
<TextBlock Text="{Binding Path=StatusText}" />
</Border>
</Grid>