วันจันทร์ที่ 10 กันยายน พ.ศ. 2555

Sort Data Using Code with the Silverlight CollectionViewSource

Sort Data Using Code with the Silverlight CollectionViewSource

As a follow-up to last week's blog posting and newsletter, this week I am going to show you how to use the CollectionViewSource object in Silverlight to sort data using code. Sometimes you need something a little more flexible, so you will need to resort to writing some code. You can take advantage of the CollectionViewSource from your XAML, but dynamically change the sort order of your lists with just a few lines of code.
For this example, I will be using a simple Product class with three properties, and a collection of Product objects using the Generic List class. Try this out by creating a Product class as shown in the following code:
public class Product
{
public Product(int id, string name, string type)
{
ProductId = id;
ProductName = name;
ProductType = type;
}
public int ProductId { get; set; }
public string ProductName { get; set; }
public string ProductType { get; set; }
}
Create a collection class that initializes a property called DataCollection with some sample data as shown in the code below:
public class Products : List<Product>
{
public Products()
{
InitCollection();
}
public List<Product> DataCollection { get; set; }
List<Product> InitCollection()
{
DataCollection = new List<Product>();
DataCollection.Add(new Product(3, "PDSA Framework", "Product"));
DataCollection.Add(new Product(1, "Haystack", "Product"));
DataCollection.Add(new Product(2, "Fundamentals of .NET eBook", "Book"));
return DataCollection;
}
}
The screen shot shown in Figure 1 is a Silverlight page that allows the user to sort the Product data by either the Product Name or the Product Type.
Sort Data Using Code
Figure 1: Sorting data using code in Silverlight
Notice that the data added to the collection is not in any particular order. Create a Silverlight page and add two XML namespaces to the UserControl.
xmlns:scm="clr-namespace:System.ComponentModel;assembly=System.Windows"
xmlns:local="clr-namespace:SLSortData"
The 'local' namespace is the name of the project that you created. The 'scm' namespace references the System.Windows.dll and is needed for the SortDescription class that you will use for sorting the data. Create a UserControl.Resources section in your Silverlight page that looks like the following:
<UserControl.Resources>
<local:Products x:Key="products" />
<CollectionViewSource x:Key="prodCollection"
Source="{Binding Source={StaticResource products},
Path=DataCollection}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="ProductName"
Direction="Ascending" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</UserControl.Resources>
The first line of code in the resources section creates an instance of your Products class. The constructor of the Products class calls the InitCollection method which creates three Product objects and adds them to the DataCollection property of the Products class. Once the Products object is instantiated you now add a CollectionViewSource object in XAML using the Products object as the source of the data to this collection. A CollectionViewSource has a SortDescriptions collection that allows you to specify a set of SortDescription objects. Each object can set a PropertyName and a Direction property. As you see in the above code you set the PropertyName equal to the ProductName property of the Product object and tell it to sort in an Ascending direction.
The two Radio Buttons on the page are created using the following xaml:
<RadioButton Name="rdoSortName"
Tag="ProductName"
Checked="SortTheData"
Content="Sort by Name" />
<RadioButton Name="rdoSortType"
Tag="ProductType"
Checked="SortTheData"
Content="Sort by Type" />
Notice the Tag attribute has been set with the name of the property that you want to sort on. The Checked attribute is set to an event procedure called SortTheData. This event procedure is shown in the following code.
private void SortTheData(object sender, RoutedEventArgs e)
{
if (lstData != null)
{
ICollectionView dataView;
dataView = (ICollectionView)lstData.ItemsSource;
dataView.SortDescriptions.Clear();
dataView.SortDescriptions.Add(
new SortDescription(((RadioButton)sender).Tag.ToString(),
ListSortDirection.Ascending));
lstData.ItemsSource = dataView;
}
}
In this code you are retrieving the CollectionViewSource data from the ItemsSource property of the list box. You cast this as a ICollectionView object. Clear any existing SortDescriptions and then add a new SortDescription object to the SortDescriptions collection on the CollectionView. You pass to the constructor of the SortDescription class the Tag property of the Radio button that was selected. Remember this is the name of the property that you wish to sort on. The second parameter passed to the constructor is the direction of the sort, either Ascending or Descending.
That's all there is to it. A simple way to allow your users to sort on different properties with just a few lines of code!
NOTE: You can download the complete sample code (in both VB and C#) at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "Sort Data Using Silverlight CollectionViewSource" from the drop-down.
 
 

วันอังคารที่ 24 กรกฎาคม พ.ศ. 2555

Custom tool warning: Cannot import wsdl:portType

I created a WCF service library project in my solution, and have service references to this. I use the services from a class library, so I have references from my WPF application project in addition to the class library. Services are set up straight forward - only changed to get async service functions.
Everything was working fine - until I wanted to update my service references. It failed, so I eventually rolled back and retried, but it failed even then! So - updating the service references fails without doing any changes to it. Why?!
The error I get is this one:
Custom tool error: Failed to generate code for the service reference 
'MyServiceReference'.  Please check other error and warning messages for details.
 The warning gives more information:
Custom tool warning: Cannot import wsdl:portType
Detail: An exception was thrown while running a WSDL import extension: 
System.ServiceModel.Description.DataContractSerializerMessageContractImporter
Error: List of referenced types contains more than one type with data contract name 'Patient' in  
namespace 'http://schemas.datacontract.org/2004/07/MyApp.Model'. Need to exclude all but one of the 
following types. Only matching types can be valid references: 
"MyApp.Dashboard.MyServiceReference.Patient, Medski.Dashboard, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" (matching)
"MyApp.Model.Patient, MyApp.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" (matching)
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:portType[@name='ISomeService']
 There are two similar warnings too saying:
Custom tool warning: Cannot import wsdl:binding
Detail: There was an error importing a wsdl:portType that the wsdl:binding is dependent on.
XPath to wsdl:portType: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:portType[@name='ISomeService']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://tempuri.org/']/wsdl:binding[@name='WSHttpBinding_ISomeService']
 And the same for:
Custom tool warning: Cannot import wsdl:port ..

When you add a service reference, there are two ways the types that are used by the service can be handled:
 •The types are stored in a dll, and that dll is referenced from both the client and the server application.
 •The types are not in a dll referenced by the client. In that case the tool that creates the service reference, will create the types in the references.cs file.

 

วันอังคารที่ 10 กรกฎาคม พ.ศ. 2555

ShowLoadingPanel

 <devx:GridControl
Grid.Row="1" x:Name="dgTest"
ShowLoadingPanel="{Binding Path=IsLoading, Mode=TwoWay}"
ItemsSource="{Binding Path=LstData, Mode=TwoWay}"
AutoPopulateColumns="False"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
AllowColumnMRUFilterList="False"
IsFilterEnabled="False">

วันจันทร์ที่ 9 กรกฎาคม พ.ศ. 2555

Expand/collapse Group when click on group header

Expand/collapse Group when click on group header

When I have a grid that groups items is there a way to expand/collapse the group when the user clicks on the text in the header? Right now the only way to expand/collapse a group is to click on the expand button in the header.

To accomplish your task handle the MouseLeftButtonUp event in the following manner:

[C#]Open in popup window
private void tableView1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) {            
TableView view = sender as TableView;            
TableViewHitInfo hi = view.CalcHitInfo(e.OriginalSource as DependencyObject);            
if (hi.HitTest == TableViewHitTest.GroupValue)                
ToggleExpandedState(view);        
}        

private void ToggleExpandedState(TableView view)        
{            
if (view.Grid.IsGroupRowExpanded(view.FocusedRowHandle))                
view.CollapseFocusedRow();            
else view.ExpandFocusedRow();        
}

วันศุกร์ที่ 22 มิถุนายน พ.ศ. 2555

Silverlight Set IE Full Screen

public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ToggleFullScreen();
        }
 
        private void ToggleFullScreen()
        {
            Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;
        }
    }

วันอาทิตย์ที่ 17 มิถุนายน พ.ศ. 2555

How to sort combind field in datagrid.

I use the code below to combine

<sdk:DataGridTemplateColumn Header="MergeColumn" Width="90">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="3,4,0,0">
<TextBlock Text="{Binding FieldA}" />
<TextBlock Text="{Binding FieldB}" />
</StackPanel>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>

วันพฤหัสบดีที่ 7 มิถุนายน พ.ศ. 2555

Xap packaging failed. Object reference not set to an instance of an object

I'm getting this error message on my PC when I try to build  Silverlight App:
Xap packaging failed. Object reference not set to an instance of an object 
I'm using Dropbox. On my laptop, It works perfectly fine and I can debug etc...

Please tried many things such as:
  • Delete obj/Debug Folder
  • Check for files which are missing on the Solution Explorer