Friday, October 14, 2011

DateTime format in .NET 4.0

Lets assume I have the DateTime pattern "dd-MMM-yyyy" in my locale.

DateTime.Now.ToString("yyyy/MM/dd") working different in 3.5 & 4.0 framework.

In 3.5, it uses the pattern given in the parameter to convert the date to string. So, the output would be "2011/11/10" and it the expected result.

But in 4.0, this would return as "2011-11-10" which is not correct. 4.0 is using the current culture's ("-") separator instead of using the pattern's separator ("/") given in the parameter. To fix it, we need to pass IFormatProvider along with the ToString function.


Example:
DateTime.Now.ToString("yyyy/MM/dd", DateTimeFormatInfo.InvariantInfo)

Friday, January 7, 2011

Different ways to bind a data in Codebind from Xaml

I see many questions in "Question & Answers" section regarding the data binding issue in WPF. And when I see the question they miss very simple thing.

This is a tip to help them out. And basically for the beginners who are trying to learn the data binding concepts.

The sample, I provide here is,
- WPF Application
- C# Language

Create a WPF Application from your Visual Studio. Place a ListBox.

XAML:

<Window x:Class="WpfApplication2.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:loc="clr-namespace:WpfApplication2"
        Title="Window1" Height="300" Width="300"
        x:Name="windowObject">
    <Grid>
        <ListBox  />
    </Grid>
</Window>

Add a simple Property in the codebehind of Window1 as CollectionOfString which is nothing but List<string>. Add few items into the CollectionOfString for our DataBinding example.

CS:

using System.Collections.Generic;using System.Windows;namespace WpfApplication2
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            this.CollectionOfString = new List<string>();
            this.CollectionOfString.Add("Apple");
            this.CollectionOfString.Add("Banana");
            this.CollectionOfString.Add("Custard Apple");
            InitializeComponent();
        }
        public List<string> CollectionOfString
        {
            get;
            set;
        }
    }
}

Now go to the designer/Xaml window. You simple set binding of the CollectionOfString in two ways like below:

Way 1:

<ListBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType={x:Type loc:Window1}},  
Path=CollectionOfString}" />

Here "loc" is the namespace of Window1 class.

Way 2:

<ListBox ItemsSource="{Binding ElementName=windowObject,  
Path=CollectionOfString}"/>

Here "windowObject" is the name of the Window

Let me know if you have any question.

I hope it is helpful.