Extend IValueConverter to create your own converter

image_pdfimage_print























//File:Window.xaml.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace WpfApplication1 {

public class Employee : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected void Notify(string propName) {
if( this.PropertyChanged != null ) {
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}

string name;
public string Name {
get { return this.name; }
set {
if( this.name == value ) { return; }
this.name = value;
Notify(“Name”);
}
}

int age;
public int Age {
get { return this.age; }
set {
if( this.age == value ) { return; }
this.age = value;
Notify(“Age”);
}
}

public Employee() { }
public Employee(string name, int age) {
this.name = name;
this.age = age;
}
}

class People : ObservableCollection { }

public partial class Window1 : System.Windows.Window {
public Window1() {
InitializeComponent();
}

}

public class AgeToRangeConverter : IValueConverter {

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
return (int)value < 25 ? "Under 25" : "Over 25"; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } [/csharp]

Debug Data Bindings Using an Empty IValueConverter

image_pdfimage_print


   
   

<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:WpfApplication1" Title="Debug Data Bindings Using an IValueConverter"  Width="200"  Height="200">
  <Window.Resources>
    <local:DummyConverter x:Key="DummyConverter" />
  </Window.Resources>
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="0.5*" />
      <RowDefinition Height="0.5*"/>
    </Grid.RowDefinitions>
    <CheckBox x:Name="chkShouldItBeOpen" IsChecked="False" Content="Open" Margin="10"/>
    <Expander IsExpanded="{Binding ElementName=chkShouldItBeOpen, Path=IsChecked,Converter={StaticResource DummyConverter}}"
      Grid.Row="1" Background="Black"  Foreground="White" Margin="10" VerticalAlignment="Center" 
      HorizontalAlignment="Center" Header="Expander!">
      <TextBlock Text="Open!" Foreground="White"/>
    </Expander>
  </Grid>
</Window>

//File:Window.xaml.cs
using System.Windows;
using System;
using System.Globalization;
using System.Windows.Data;
namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }

    public class DummyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }

        public object ConvertBack(object value,Type targetType,object parameter,CultureInfo culture)
        {
            return value;
        }
    }
}

   
    
    
     


Use LengthConverter

image_pdfimage_print


   
   



<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="Canvas_Positioning_Properties.Window1"
    Title="Canvas Positioning Properties">
  <StackPanel>
    <Canvas Name="canvas1" Height="300">
        <TextBlock Name="text1" FontWeight="Bold" Canvas.Left="0" Canvas.Right="0" Canvas.Top="0" Canvas.Bottom="0">A TextBlock.</TextBlock>
  </Canvas>
    <ListBox Grid.Column="3" Grid.Row="1" VerticalAlignment="Top" Width="60" Margin="10,0,0,0" SelectionChanged="ChangeLeft">

      <ListBoxItem>Auto</ListBoxItem>      
      <ListBoxItem>10</ListBoxItem>
      <ListBoxItem>20</ListBoxItem>
      <ListBoxItem>30</ListBoxItem>
      <ListBoxItem>40</ListBoxItem>
      <ListBoxItem>50</ListBoxItem>
      <ListBoxItem>60</ListBoxItem>
      <ListBoxItem>70</ListBoxItem>
      <ListBoxItem>80</ListBoxItem>
      <ListBoxItem>90</ListBoxItem>
      <ListBoxItem>100</ListBoxItem>      
    </ListBox>
  </StackPanel>        
</Window>
//File:Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Data;

namespace Canvas_Positioning_Properties
{

  public partial class Window1 : Window
  {
    public void ChangeLeft(object sender, SelectionChangedEventArgs args)
    {
      ListBoxItem li = ((sender as ListBox).SelectedItem as ListBoxItem);
      LengthConverter myLengthConverter = new LengthConverter();
      Double db1 = (Double)myLengthConverter.ConvertFromString(li.Content.ToString());
      Canvas.SetLeft(text1, db1);
      Console.WriteLine(myLengthConverter.ConvertToString(Canvas.GetLeft(text1)));
    }


  }
}

   
    
    
     


Color Converter

image_pdfimage_print
   
 
//http://aspascension.codeplex.com/
//Microsoft Public License (Ms-PL)

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.Reflection;
using System.Windows.Data;

namespace ASPAscension.Silverlight.Converters
{
    public class ColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value.GetType() == typeof(String))
            {
                string val = value as string;
                Color c;
                if (val.StartsWith("#"))
                {
                    val = val.Replace("#", "");  
                    byte a = System.Convert.ToByte("ff", 16);  
                    byte pos = 0;  
                    if (val.Length == 8)  
                    {  
                        a = System.Convert.ToByte(val.Substring(pos, 2), 16);  
                        pos = 2;  
                    }  
                    byte r = System.Convert.ToByte(val.Substring(pos, 2), 16);  
                    pos += 2;  
                    byte g = System.Convert.ToByte(val.Substring(pos, 2), 16);  
                    pos += 2;  
                    byte b = System.Convert.ToByte(val.Substring(pos, 2), 16);  
                    c = Color.FromArgb(a, r, g, b);  
                    return new SolidColorBrush(c);
                }
                else
                {
                    try
                    {
                        c = GetColorFromString(value as string);
                        return new SolidColorBrush(c);
                    }
                    catch (InvalidCastException ex)
                    {
                        return null;
                    }
                }
            }
            return null;
        }

        public static Color GetColorFromString(string colorString)
        {
            Type colorType = (typeof(System.Windows.Media.Colors));
            if (colorType.GetProperty(colorString) != null)
            {
                object color = colorType.InvokeMember(colorString, BindingFlags.GetProperty, null, null, null);
                try
                {
                    return (Color)color;
                }
                catch
                {
                    throw new InvalidCastException("Color not defined");
                }
            }
            return Colors.Transparent;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            SolidColorBrush val = value as SolidColorBrush;
            return val.Color.ToString();
            //if (typeof(Colors).GetProperty(val.Color.ToString()) != null)
            //    return typeof(Colors).GetProperty(val.Color.ToString()).GetValue(val, null);
            //else
            //    return "#" + val.Color.A.ToString() + val.Color.R.ToString() + val.Color.G.ToString() + val.Color.B.ToString();
        }
    }
}

   
     


Write Jpeg file from BitmapSource

image_pdfimage_print
   
 
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Media.Imaging;
using System.IO;

    class UseBitmapCodecs
    {
        static void WriteJpeg(string fileName, int quality, BitmapSource bmp)
        {

            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            BitmapFrame outputFrame = BitmapFrame.Create(bmp);
            encoder.Frames.Add(outputFrame);
            encoder.QualityLevel = quality;

            using (FileStream file = File.OpenWrite(fileName))
            {
                encoder.Save(file);
            }
        }
    }

   
     


Use JpegBitmapDecoder

image_pdfimage_print
   
 
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Media.Imaging;
using System.IO;

    class UseBitmapCodecs
    {
        static string GetCamera(string myJpegPath)
        {
            JpegBitmapDecoder decoder = new JpegBitmapDecoder(new Uri(myJpegPath),BitmapCreateOptions.None, BitmapCacheOption.None);
            BitmapMetadata bmpData = (BitmapMetadata) decoder.Frames[0].Metadata;
            return bmpData.CameraModel;
        }
    }

   
     


Set opacity for Image

image_pdfimage_print


   
     
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF" Height="300" Width="400">
    <StackPanel Orientation="Horizontal">
        <Image Margin="-30" Opacity=".7" Source="c:image.gif" 
               ToolTip="Middle Image" Width="150" />
    </StackPanel>
</Window>