Latest Entries »

Save UIElement as PNG in Silverlight 3

We don’t have printing feature in SL 3 (SL 4 has that feature though :-) ) so here’s the workaround solution – create a bitmap file of that UIElement then Save that file to user local machine.

Code get from here http://forums.silverlight.net/forums/p/114691/446894.aspx


public static void GenerateImage(UIElement toPrint,double ActualHeight, double ActualWidth )
        {
            WriteableBitmap bitmap = new System.Windows.Media.Imaging.WriteableBitmap(Convert.ToInt32(ActualWidth),
                                                                                    Convert.ToInt32(ActualHeight));

            bitmap.Render(toPrint, new TranslateTransform());
            bitmap.Invalidate();
            SaveFile(bitmap);
        }

        #region Save file

        private static void SaveFile(WriteableBitmap wb)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.DefaultExt = "png";
            saveFileDialog.Filter = "PNG Files (*.png)|*.png|All files (*.*)|*.*";
            saveFileDialog.FilterIndex = 1;

            if (saveFileDialog.ShowDialog() == true)
            {

                using (Stream stream = saveFileDialog.OpenFile())
                {

                    byte[] buffer = GetBuffer(wb);
                    stream.Write(buffer, 0, buffer.Length);

                    stream.Close();
                }

            }
        }

        private static byte[] GetBuffer(WriteableBitmap bitmap)
        {
            int width = bitmap.PixelWidth;
            int height = bitmap.PixelHeight;

            MemoryStream ms = new MemoryStream();

            #region BMP File Header(14 bytes)
            //the magic number(2 bytes):BM
            ms.WriteByte(0x42);
            ms.WriteByte(0x4D);

            //the size of the BMP file in bytes(4 bytes)
            long len = bitmap.Pixels.Length * 4 + 0x36;

            ms.WriteByte((byte)len);
            ms.WriteByte((byte)(len >> 8));
            ms.WriteByte((byte)(len >> 16));
            ms.WriteByte((byte)(len >> 24));

            //reserved(2 bytes)
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);

            //reserved(2 bytes)
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);

            //the offset(4 bytes)
            ms.WriteByte(0x36);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            #endregion

            #region Bitmap Information(40 bytes:Windows V3)
            //the size of this header(4 bytes)
            ms.WriteByte(0x28);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);

            //the bitmap width in pixels(4 bytes)
            ms.WriteByte((byte)width);
            ms.WriteByte((byte)(width >> 8));
            ms.WriteByte((byte)(width >> 16));
            ms.WriteByte((byte)(width >> 24));

            //the bitmap height in pixels(4 bytes)
            ms.WriteByte((byte)height);
            ms.WriteByte((byte)(height >> 8));
            ms.WriteByte((byte)(height >> 16));
            ms.WriteByte((byte)(height >> 24));

            //the number of color planes(2 bytes)
            ms.WriteByte(0x01);
            ms.WriteByte(0x00);

            //the number of bits per pixel(2 bytes)
            ms.WriteByte(0x20);
            ms.WriteByte(0x00);

            //the compression method(4 bytes)
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);

            //the image size(4 bytes)
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);

            //the horizontal resolution of the image(4 bytes)
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);

            //the vertical resolution of the image(4 bytes)
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);

            //the number of colors in the color palette(4 bytes)
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);

            //the number of important colors(4 bytes)
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            #endregion

            #region Bitmap data
            for (int y = height - 1; y >= 0; y--)
            {
                for (int x = 0; x < width; x++)
                {
                    int pixel = bitmap.Pixels[width * y + x];

                    ms.WriteByte((byte)(pixel & 0xff)); //B
                    ms.WriteByte((byte)((pixel >> 8) & 0xff)); //G
                    ms.WriteByte((byte)((pixel >> 0x10) & 0xff)); //R
                    ms.WriteByte(0x00); //reserved
                }
            }
            #endregion


            return ms.GetBuffer();
        }

        #endregion 

Windows Phone 7

Get Location

http://timheuer.com/blog/archive/2010/03/22/geo-location-services-in-windows-phone-7-developer-emulator.aspx

Direction or Vibration

http://www.codeproject.com/Articles/71084/Using-the-GPS-Accelerometer-Vibration-Controller.aspx

http://blog.enterprisemobile.com/2008/07/using-htc-diamonds-sensor-sdk-from-managed-code/

Page transaction:

http://slickthought.net/post/2010/05/20/Windows-Phone-7-April-CTP-and-TransitioningContentControl.aspx


Sample Data:

UDCC : [ UL 42.025187,-93.651941 , UR 42.025201,-93.651141 ,
DL 42.024764,-93.651935 , DR 42.02476,-93.651152 ]

My Location: 42.025046,-93.650981

Will display building name only if the distance from My Location to that building <= 10 feet ( around 3m)

Copy and Paste from http://www.silverlighttips.com/post/2009/10/08/SilverlightValidationTextBox.aspx

The built-in validation in Silverlight 3.0 is a great new feature that can be used on essential Silverlight controls such as TextBox. Using this feature, it is possible to nicely display an error message and highlight the TextBox that has bad value.

In this post I will only cover validating data in TextBox controls, which are simply used in most forms to receive basic information such as Name, Surname and Email address. The completed and working version of this project can be downloaded from CodePlex from here. I will explain and provide solution on how to validate ComboBox, Radio Button controls or etc in another post soon, so please keep yourself updated on new posts here.

1. Create a basic form with a few TextBox controls in the xaml

2. Create a class, call it CustomValidation
Add the following code to your CustomValidation class:

private string message;
public CustomValidation(string message)
{
this.message = message;
}
public bool ShowErrorMessage
{
get;
set;
}
public object ValidationError
{
get
{
return null;
}
set
{
if (ShowErrorMessage)
{
throw new ValidationException(message);
}
}
}

3. Create an Extension class (Extensions)
To understand what is an Extension class and for more information about them visit my tutorial post “Extension methods in Silverlight and C#”.

In brief: Extensions will be your Extension class to extend any object of type FrameworkElement like TextBox controls within your application framework. It means you can use the public methods within this class as a “built-in” method for your TextBox.

Create a static public method and call it SetValidation. This method receives an instance of a FrameWorkElement and a string value, and returns nothing:

public static void SetValidation(this FrameworkElement frameworkElement, string message)
{
CustomValidation customValidation = new CustomValidation(message);
Binding binding = new Binding("ValidationError")
{
Mode = System.Windows.Data.BindingMode.TwoWay,
NotifyOnValidationError = true,
ValidatesOnExceptions = true,
Source = customValidation
};
frameworkElement.SetBinding(Control.TagProperty, binding);
}

CustomValidation is the class we defined earlier.

“Binding” is a class in System.Windows.Data assembly which gets or sets a value that indicates whether to raise the error attached event on the bound object.

What are we doing? Here we have a CustomValidation class that has one property (“ShowErrorMessage”) and one public methods (“ValidationError”). “ValidationError” is our source binding object and what we want to be able to do in the future is to bind our frameworkElement, which is a TextBox, to ValidationError. We are in simple words binding the CustomValidation class to our TextBox once we call this method on our TextBox.

For more information on Binding and BindingExpression visi msdn article here.

Create another two methods for displaying validation error and also for clearing validation error when the error was corrected:

public static void RaiseValidationError(this FrameworkElement frameworkElement)
{
BindingExpression b =
frameworkElement.GetBindingExpression(Control.TagProperty);
if (b != null)
{
((CustomValidation)b.DataItem).ShowErrorMessage = true;
b.UpdateSource();
}
}

public static void ClearValidationError(this FrameworkElement frameworkElement)
{
BindingExpression b =
frameworkElement.GetBindingExpression(Control.TagProperty);
if (b != null)
{
((CustomValidation)b.DataItem).ShowErrorMessage = false;
b.UpdateSource();
}
}

By creating a new BindingExpression you will be creating an instance of your binding so you can control the properties and public methods of your binding source/target. In above case, we are casting the BindingExpression.DataItem as CustomValidation. This enables us to access the properties of this class, “ShowErrorMessage” in this case.

4. RaiseValidationError() and ClearValidationError()
So now we have our TextBox, a method in our Extension class to bind the TextBox to our CustomValidation class and passes our error message, and a method in our Extension class that fires throw new ValidationException(message); from the CustomValidation class.

All we need to do now is to check if a specific TextBox is valid or not. If the TextBox was not valid we can simply use the RaiseValidationError() and ClearValidationError() methods, which should now be available from the intellisense in Visual Studio, to throw the validation exception and display a suitable error message and we do that by following code when the submit button was pressed:

Name.ClearValidationError();
bool isFormValid = true;
if (Name.Text == "")
{
Name.SetValidation("Please enter your name");
Name.RaiseValidationError();
isFormValid = false;
}

use isFormValid variable to check if you have to submit the form or not. The Name.ClearValidationError() makes sure you clear the form everytime you press submit, so if the form was valid the error message had already been cleaned.

I have some extra validation extensions on this project and have organised the code in different class files.
Download the project from here.

Silverlight Navigation

I found an interesting post about Navigation framework in Silverlight by Tim Heuer and here’s some codes that I made based on that tutorial. ( the codes may have some differences compare to Tim codes since I used Silverlight 4 while Tim used older version of SL.

MainPage.xaml

<UserControl x:Class=”DesktopApp.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:navigation=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation”
mc:Ignorable=”d”>

<Grid x:Name=”LayoutRoot” Background=”White”>

<StackPanel Orientation=”Horizontal” VerticalAlignment=”Top”>
<StackPanel Orientation=”Vertical” Width=”250″>
<HyperlinkButton Content=”Home” FontFamily=”24″ Click=”HyperlinkButton_Click” Tag=”/Home”/>
<HyperlinkButton Content=”About” FontFamily=”24″ Click=”HyperlinkButton_Click” Tag=”/About”/>
<HyperlinkButton Content=”Customers” FontFamily=”24″ Click=”HyperlinkButton_Click” Tag=”/CustomerList”/>

</StackPanel>

<navigation:Frame x:Name=”MainFrame” HorizontalContentAlignment=”Stretch” VerticalContentAlignment=”Stretch”
Margin=”20″ Source=”/Home” UriMapper=”{StaticResource uriMapper}”/>
</StackPanel>

</Grid>
</UserControl>


MainPage.xaml.cs

namespace DesktopApp
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}

private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
{
HyperlinkButton btn = sender as HyperlinkButton;
string url = btn.Tag.ToString();
this.MainFrame.Navigate(new Uri(url, UriKind.Relative));
}
}
}

App.xaml (for URI mapping)

<Application xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
x:Class=”DesktopApp.App”
xmlns:navcore=”clr-namespace:System.Windows.Navigation;assembly=System.Windows.Controls.Navigation”
>
<Application.Resources>
<navcore:UriMapper x:Key=”uriMapper”>
<navcore:UriMapping Uri=”/Home” MappedUri=”/Views/Home.xaml” />
<navcore:UriMapping Uri=”/About” MappedUri=”/Views/About.xaml” />
<navcore:UriMapping Uri=”/CustomerList” MappedUri=”/Views/CustomerList.xaml”/>
<navcore:UriMapping Uri=”/Customer/{id}” MappedUri=”/Views/CustomerDetail.xaml?id={id}” />

</navcore:UriMapper>
</Application.Resources>
</Application>

Views/Home.xaml

<navigation:Page x:Class=”DesktopApp.Views.Home”
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=”640″ d:DesignHeight=”480″
Title=”Home Page”>
<Grid x:Name=”LayoutRoot”>
<TextBlock Text=”Home Information” FontSize=”24″/>
</Grid>
</navigation:Page>

Views/About.xaml

<navigation:Page x:Class=”DesktopApp.Views.About”
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=”640″ d:DesignHeight=”480″
Title=”About US”>
<Grid x:Name=”LayoutRoot”>
<TextBlock Text=”About Us Information” FontSize=”24″/>

</Grid>
</navigation:Page>

Views/CustomerList.xaml

<navigation:Page x:Class=”DesktopApp.Views.CustomerList”
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=”640″ d:DesignHeight=”480″
Title=”Customers Information”>
<Grid x:Name=”LayoutRoot”>
<ItemsControl x:Name=”customerListing”>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation=”Horizontal”>
<HyperlinkButton Content=”{Binding ID}” Tag=”{Binding ID}” Click=”HyperlinkButton_Click”/>
<TextBlock Text=”{Binding FirstName}” Margin=”5,0,0,0″ />
<TextBlock Text=”{Binding LastName}” Margin=”5,0,0,0″ />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</navigation:Page>

Views/CustomerList.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using DesktopApp.Models;
namespace DesktopApp.Views
{
public partial class CustomerList : Page
{

public CustomerList()
{
InitializeComponent();
Loaded+=new RoutedEventHandler(CustomerList_Loaded);
}

void CustomerList_Loaded(object sender, RoutedEventArgs e)
{
Customers customerList = new Customers();
customerListing.ItemsSource = customerList.GetAllCustomers();

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

private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
{
HyperlinkButton btn = sender as HyperlinkButton;
int id = Convert.ToInt32(btn.Tag);
this.NavigationService.Navigate(new Uri(string.Format(“/Customer/{0}”, id), UriKind.Relative));
}

}
}

Views/CustomerDetail.xaml

<navigation:Page x:Class=”DesktopApp.Views.CustomerDetail”
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=”640″ d:DesignHeight=”480″
Title=”Customer Detail”>
<Grid x:Name=”LayoutRoot”>
<StackPanel Orientation=”Vertical”>
<TextBlock x:Name=”FirstName” Text=”{Binding FirstName}” />
<TextBlock x:Name=”LastName” Text=”{Binding LastName}” />
</StackPanel>
</Grid>
</navigation:Page>

Views/CustomerDetail.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using DesktopApp.Models;

namespace DesktopApp.Views
{
public partial class CustomerDetail : Page
{
public CustomerDetail()
{
InitializeComponent();
Loaded+=new RoutedEventHandler(CustomerDetail_Loaded);
}

void CustomerDetail_Loaded(object sender, RoutedEventArgs e)
{
Customers c = new Customers();
int id = Convert.ToInt32(this.NavigationContext.QueryString["id"]);
FirstName.Text= c.GetCustomer(id).FirstName;
LastName.Text = c.GetCustomer(id).LastName;
}

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

}
}

Models/Customers.cs

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.Collections.Generic;
using System.Collections.ObjectModel;

namespace DesktopApp.Models
{
public class Customers
{
ObservableCollection<Customer> lstCustomer = new ObservableCollection<Customer>();

public Customers()
{
lstCustomer.Add(new Customer() { ID = 1, FirstName = “Minh”, LastName =”Dong” });
lstCustomer.Add(new Customer() { ID = 2, FirstName = “Silverlight”, LastName = “.Net” });
lstCustomer.Add(new Customer() { ID = 3, FirstName = “Tim”, LastName = “Heuer” });
}

public ObservableCollection<Customer> GetAllCustomers()
{
return lstCustomer;
}

public Customer GetCustomer(int id)
{
if(lstCustomer.Count > 0)
{
foreach (Customer c in lstCustomer)
{
if (c.ID == id)
{
return c;
}
}
return null;
}
return null;
}
}
public class Customer
{
public string FirstName { set; get; }
public string LastName { set; get; }
public int ID { set; get; }
}
}

ColumnDefinition column = new ColumnDefinition();
column.Width = System.Windows.GridLength.Auto;

layoutRoot.ColumnDefinitions.Add(column);

layoutRoot.Children.Add(btnTest);
Grid.SetColumn(btnTest, (layoutRoot.ColumnDefinitions.Count-1));

————————————————

In Silverlight, if we want to dynamically add controls to our page, we may think in this way:

  • <Grid> : so we can add columns, rows by using Grid.SetColumn(<elementToAdd>,<columnNumber>)
  • <StackPanel>: So we can set the orientation (Vertical or Horizontal) of the elements we add in that stackpanel

//This method will return the list of all controls of a specific type in our root layout

private IEnumerable<DependencyObject> GetControls(DependencyObject root)
{
List<DependencyObject> doList = new List<DependencyObject>();
doList.Add(root);
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
doList.AddRange(GetControls(VisualTreeHelper.GetChild(root, i)));

return doList;

}

//Here’s how we use it, LayoutRoot here is a Grid

private void OKButton_Click(object sender, RoutedEventArgs e)
{
var txtBoxes = GetControls(LayoutRoot).OfType&lt;TextBox&gt;();
foreach (var txtBox in txtBoxes)
{
lstTextBoxes.Add(txtBox);
}

this.DialogResult = true;
}

Thank to Pete for this great tip ( http://10rem.net/blog/2010/04/18/silverlight-and-wpf-tip-fitting-items-in-a-listbox )

One layout issue many folks run into in WPF and Silverlight is the problem of ListBox content not automatically sizing to the width of the ListBox.

Using my WPF Twitter Application video as an example, here’s a shot with it with the items not fitting correctly. Compare to the second screen shot, and you can see the text has scrolled off the right of the ListBox.

image

Here’s a shot with the ListBox fixed, and the items all fit in place. Notice that the text has wrapped and there is no horizontal scrollbar.

image

Luckily, the solution is pretty simple: You just need to do four things, but because it is a combination of these things, the solution often eludes folks:

  1. Use a grid as the root element of your ItemTemplate/DataTemplate
  2. Tell the ListBox to disable horizontal scrolling.
  3. Wrap or clip any text
  4. Use * sizing, not Auto sizing for variable width columns

Here’s the updated Xaml. Note the highlighted lines.

<ListBox Margin="12,83,12,12"
            Name="listBox1"
            ScrollViewer.HorizontalScrollBarVisibility="Disabled"
            ItemsSource="{Binding Path=Tweets}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <!-- In the video, this is in a UserControl. That's still ok to do. -->
            <Grid Margin="10">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>

                <Image Source="{Binding Path=FromImage}"
                        Height="70"
                        VerticalAlignment="Top"
                        Grid.RowSpan="2" />
                <TextBlock Text="{Binding Path=From}"
                            Grid.Column="1" />
                <TextBlock Text="{Binding Path=Text}"
                            TextWrapping="Wrap"
                            Grid.Column="1"
                            Grid.Row="1" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Here’s an explanation of why:

1. Use a Grid

The Grid is the most powerful and flexble of the standard panel controls. It also has provisions to ensure that it stays at a width which does not exceed what it has been allowed. If you use another panel, they may stretch their content to the right and otherwise not behave well in a listbox.

2. Disable Horizontal Scrolling

When horizontal scrolling is enabled, the listbox allows the content to be any width. When disabled, the listbox constrains the items width to be the visible width on-screen.

3. Wrap or Trim, or Clip Text

When #1 and #2 are in place, but you do not wrap text, the text will simply be truncated. If you trim it (using TextTrimming) or clip it (using the default clip or your own), the text will take up only the amount of space you want it to. This isn’t required to get layout to work the way you want, but it is required to get the result to look the way you want.

4. Use Star Sizing instead of Auto Sizing for Width

If you set the width of your grid columns to be “Auto” for the bits that are pushing out the horizontal size of the template, Silverlight and WPF will gladly give your grid all the room it needs. “Auto” means, “give me what I want”. If you set it to “*” (Star), the grid will give your element the room that is available. If you set the variable-width column to a fixed number, you will always get that size, even if the ListBox doesn’t really have it. Always set the columns containing variable-width content to have a Width of * or a multiple of * like 2* if your layout is more complex. The other items can have Auto or fixed (a number) width.

That’s all there is to it. This will solve 90% of the ListBox sizing issues out there. If it’s not working for you, start dismantling your DataTemplate element-by-element and see if you’ve got something in there that’s forcing the list box item to be a wider width.

Using C# and LINQ to read feed

//1

Using System.Xml.Linq;

//2

XDocument feedXML = XDocument.Load("http://ask.metafilter.com/158740/You-were-doing-it-wrong/rss");

//3
var feeds = from feed in feedXML.Descendants("item")
select new
{
User = feed.Element("dc:creator"),
Content = feed.Element("description"),
PubDate = feed.Element("pubDate")
};

//4
foreach (var feed in feeds) 
{     
      Console.WriteLine("User:{0}, Date{1}",  feed.User.Value,  feed.PubDate.Value  ); 
}

DONE

import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.Map.Entry;

public class test {

/**
* @param args
*/
public static void main(String[] args) {

HashMap cost = new HashMap();
cost.put(1,5);
cost.put(2,4);
cost.put(3,1);
cost.put(4,7);

PriorityQueue> edgeQueue = new PriorityQueue>(10,
new Comparator>(){

@Override
public int compare(Entry o1, Entry o2) {

return o1.getValue().compareTo(o2.getValue());
}

}
);

Iterator> iter = cost.entrySet().iterator();
while(iter.hasNext()){
edgeQueue.add(iter.next());
}

while(!edgeQueue.isEmpty()){
System.out.println(edgeQueue.remove());
}
}

}

//Don’t iterate through the Priority Queue since the behavior maybe unexpected, try to use remove instead

Install Xcode
Download Eclipse + CDT

Note: If error “unresolved inclusion” appears next to #include statement, the “include paths for headers” are not set properly.
Right click the project ⇒ Property ⇒ C/C++ General ⇒ Paths and Symbols ⇒ Includes ⇒ GNU C ⇒ Add… ⇒
Enter
“/usr/include”
“/usr/local/include”
“/usr/lib/gcc/i686-apple-darwin10/4.2.1/include”

⇒ GNU C++ ⇒ Add… ⇒
Enter
“/usr/include/c++/4.2.1″
“/usr/include/c++/4.2.1/i686-apple-darwin10/x86_64″
“/usr/include/c++/4.2.1/backward”
“/usr/local/include”
“/usr/lib/gcc/i686-apple-darwin10/4.2.1/include”
“/usr/include”

Note: For Lauched failed. Binary Not Found

1/ Project->Properties->C/C++ Build->Settings->Binary Parsers
For the mac select Mach-O Parser.

2/ Go to project Properties, C/C++ Build, Settings
then click on Miscellaneous under Mac OS X C++ Linker and put “-arch i386″ in the Linker Flag Box
and then Miscellaneous under gcc c++ compiler and put the same: “-arch i386″ in the Other Flags box.

Since: Standard g++ compilation has moved to 64 bit instead of 32 bit on Snow Leopard.
Mach-0 can’t read 64 bit binaries yet though.
Just change your compiler and linking flags in Eclipse and add “-arch i386″.

Follow

Get every new post delivered to your Inbox.