Mega Code Archive

 
Categories / Silverlight / Data
 

Add a value converter to a binding using XAML

<UserControl x:Class='SilverlightApplication3.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'      mc:Ignorable='d'      d:DesignWidth='640'      d:DesignHeight='480'     xmlns:c="clr-namespace:SilverlightApplication3">      <StackPanel>   <StackPanel.Resources>     <c:MyData x:Key="myDataSource"/>     <c:MyConverter x:Key="MyConverterReference"/>     <Style TargetType="TextBlock">       <Setter Property="FontSize" Value="15"/>       <Setter Property="Margin" Value="3"/>     </Style>   </StackPanel.Resources>      <StackPanel.DataContext>     <Binding Source="{StaticResource myDataSource}"/>   </StackPanel.DataContext>   <TextBlock Text="Unconverted data:"/>   <TextBlock Text="{Binding Path=TheDate}"/>   <TextBlock Text="Converted data:"/>   <TextBlock Name="myconvertedtext" Foreground="{Binding Path=TheDate,Converter={StaticResource MyConverterReference}}">     <TextBlock.Text>       <Binding Path="TheDate" Converter="{StaticResource MyConverterReference}"/>     </TextBlock.Text>   </TextBlock> </StackPanel> </UserControl> //File:Window.xaml.cs using System; using System.Globalization; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Data; using System.Windows.Media; namespace SilverlightApplication3 {   public class MyConverter : IValueConverter   {     public object Convert(object o, Type type,object parameter, CultureInfo culture){         DateTime date = (DateTime)o;         switch (type.Name)         {             case "String":                 return date.ToString("F", culture);             default:                 return o;         }     }     public object ConvertBack(object o, Type type,object parameter, CultureInfo culture){         return null;     }   }   public class MyData: INotifyPropertyChanged{     private DateTime thedate;     public MyData(){       thedate = DateTime.Now;     }     public DateTime TheDate     {       get{return thedate;}       set{         thedate = value;         OnPropertyChanged("TheDate");       }     }     public event PropertyChangedEventHandler PropertyChanged;     private void OnPropertyChanged(String info)     {       if (PropertyChanged !=null)       {         PropertyChanged(this, new PropertyChangedEventArgs(info));       }     }   } }