views:

13

answers:

1

I have a date picker in my xaml file and also a text box When the user enters the DOB age should be calculated and it should be displayed in the text box .

Can anybody help me ?

+1  A: 

You can bind the date picker's SelectedDate to the date property of your data context and bind the Text property of the TextBox (TextBlock?) to an Age property.

You'll probably also want to implement INotifyPropertyChanged on your data context class and to call PropertyChanged('Age') when DateOfBirth is updated

For instance (this is a very simple example, find documentation on MVVM for more)

Person class:

namespace SilverlightApplication1
{
    public class Person : INotifyPropertyChanged
    {
        public Person()
        {
            DateOfBirth = new DateTime(1980, 12, 5);
        }

        public DateTime DateOfBirth
        {
            get
            {
                return _dateOfBirth;
            }

            set
            {
                _dateOfBirth = value;
                RaisePropertyChanged("DateOfBirth");
                RaisePropertyChanged("Age");
            }
        }

        private DateTime _dateOfBirth;

        public int Age { get { return GetAge(DateOfBirth); } }

        private int GetAge(DateTime dateOfBirth)
        {
            DateTime now = DateTime.Today;
            int result = now.Year - dateOfBirth.Year;
            if (dateOfBirth > now.AddYears(-result))
            {
                result--;
            }

            return result;
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

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

        #endregion
    }
}

Used in the following XAML:

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

    <UserControl.Resources>
        <local:Person x:Key="Person"></local:Person>
    </UserControl.Resources>

    <StackPanel Orientation="Vertical" DataContext="{StaticResource Person}">
        <sdk:DatePicker SelectedDate="{Binding DateOfBirth, Mode=TwoWay}"/>
        <TextBlock Text="{Binding Age}"/>
    </StackPanel>
</UserControl>
vc 74