Debug Data Bindings Using an Empty IValueConverter


   
   

<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;
        }
    }
}

   
    
    
     


Extend IValueConverter to create your own converter























//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]

Decimal ScrollBar Window with extending IValueConverter


   
   
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:MyNameSpace.DecimalScrollBar" 
        Title="Decimal ScrollBar">
    <Window.Resources>
        <src:DoubleToDecimalConverter x:Key="conv" />
    </Window.Resources>
    <StackPanel>
        <ScrollBar Name="scroll"
                   Orientation="Horizontal" Margin="24" 
                   Maximum="100" LargeChange="10" SmallChange="1" />
        <Label HorizontalAlignment="Center" 
               Content="{Binding ElementName=scroll, Path=Value, 
                    Converter={StaticResource conv}, ConverterParameter=2}" />
    </StackPanel>
</Window>
//File:Window.xaml.cs
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace MyNameSpace.DecimalScrollBar
{
    [ValueConversion(typeof(double), typeof(decimal))]
    public class DoubleToDecimalConverter : IValueConverter
    {
        public object Convert(object value, Type typeTarget,object param, CultureInfo culture)
        {
            decimal num = new Decimal((double)value);

            if (param != null)
                num = Decimal.Round(num, Int32.Parse(param as string));

            return num;
        }
        public object ConvertBack(object value, Type typeTarget, 
                                  object param, CultureInfo culture)
        {
            return Decimal.ToDouble((decimal)value);
        }
    }
}

   
    
    
     


IMultiValueConverter and IValueConverter


   
   

<Window x:Class="ColorConverter.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:ColorConverter"
    Title="Colors" Height="300" Width="300">
  <Window.Resources>
    <local:ColorMultiConverter x:Key="colorConverter"/>
    <local:ColorNameValueConverter x:Key="colorNameConverter"/>
  </Window.Resources>
  <Grid>
    <Label Name="label1" Width="39">Red:</Label>
    <Slider Name="redSlider" VerticalAlignment="Top" Maximum="255" />
    <Label Name="label2">Green:</Label>
    <Slider Name="greenSlider" Maximum="255" />
    <Label Name="label3">Blue:</Label>
    <Slider Name="blueSlider" Maximum="255" />
    <Grid Name="colorBlock" >
        <Grid.Background>
          <SolidColorBrush>
            <SolidColorBrush.Color>
              <MultiBinding Converter="{StaticResource colorConverter}">
                <Binding ElementName="redSlider" Path="Value"/>
                <Binding ElementName="greenSlider" Path="Value"/>
                <Binding ElementName="blueSlider" Path="Value"/>
              </MultiBinding>
            </SolidColorBrush.Color>
          </SolidColorBrush>
        </Grid.Background>
        <Label Name="label4" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" >
          <Label.Foreground>
            <SolidColorBrush>
              <SolidColorBrush.Color>
                <MultiBinding Converter="{StaticResource colorConverter}" ConverterParameter="inverse">
                  <Binding ElementName="redSlider" Path="Value"/>
                  <Binding ElementName="greenSlider" Path="Value"/>
                  <Binding ElementName="blueSlider" Path="Value"/>
                </MultiBinding>
              </SolidColorBrush.Color>
            </SolidColorBrush>
          </Label.Foreground>
          <Label.Content>
            <PriorityBinding FallbackValue="Unknown">
              <Binding ElementName="colorBlock" Path="Background.Color" Converter="{StaticResource colorNameConverter}"/>
              <Binding ElementName="colorBlock" Path="Background.Color"/>
            </PriorityBinding>
          </Label.Content>
        </Label>
    </Grid>
  </Grid>
</Window>

//File:Window.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
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.Navigation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Windows;
using System.Reflection;


namespace ColorConverter
{
  public partial class Window1 : Window
  {
    public Window1()
    {
      InitializeComponent();
    }

    private void colorBlock_MouseDown(object sender, MouseButtonEventArgs e)
    {
      Random rnd = new Random((int)DateTime.Now.Ticks);

      Color newColor = Color.FromRgb((byte)rnd.Next(255), (byte)rnd.Next(255), (byte)rnd.Next(255));
      colorBlock.Background = new SolidColorBrush(newColor);
    }
  }
  class ColorMultiConverter : IMultiValueConverter
  {

    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      bool inverse = (parameter != null) &amp;&amp; (string.Compare(parameter.ToString(), "inverse", true) == 0);

      byte R = System.Convert.ToByte((double)values[0]);
      byte G = System.Convert.ToByte((double)values[1]);
      byte B = System.Convert.ToByte((double)values[2]);

      Color newColor;
      if (inverse)
        newColor = Color.FromRgb((byte)(255 - R), (byte)(255 - G), (byte)(255 - B));
      else
        newColor = Color.FromRgb(R, G, B);

      return newColor;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
      Color oldColor = (Color)value;
      double R = (double)oldColor.R;
      double G = (double)oldColor.G;
      double B = (double)oldColor.B;

      return new object[] { R, G, B };
    }

  }

  class ColorNameValueConverter : IValueConverter
  {
    private Dictionary<Color, string> namedColors = new Dictionary<Color, string>();

    public ColorNameValueConverter()
    {
      PropertyInfo[] colorProperties = typeof(Colors).GetProperties(BindingFlags.Static | BindingFlags.Public);
      Color stepColor;
      foreach (PropertyInfo pi in colorProperties)
      {
        if (pi.PropertyType == typeof(Color))
        {
          stepColor = (Color)pi.GetValue(null, null);
          namedColors[stepColor] = pi.Name;
        }
      }
    }
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      Color col = (Color)value;
      if(namedColors.ContainsKey(col))
        return namedColors[col];
      return DependencyProperty.UnsetValue;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      throw new NotImplementedException();
    }
  }  
}

   
    
    
     


Bind to XML Data embed the data directly


   
 
<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="240" Width="200">
    <Window.Resources>
        <XmlDataProvider x:Key="CountriesXML">
            <x:XData>
                <Countries xmlns="">
                    <Country Name="Great Britan" Continent="Europe" />
                    <Country Name="USA" Continent="NorthAmerica" />
                    <Country Name="Canada" Continent="NorthAmerica" />
                </Countries>
            </x:XData>
        </XmlDataProvider>
    </Window.Resources>
    <Grid>
        <ListBox
            ItemsSource="{Binding Source={StaticResource CountriesXML}, XPath=/Countries/Country/@Name}"    
        />
    </Grid>
</Window>

   
     


Set DisplayMemberPath for ItemsControl


   
  

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:WpfApplication1="clr-namespace:WpfApplication1"
     Title="WPF" Height="294" Width="160">
    <Window.Resources>
        <WpfApplication1:Countries x:Key="countries"/>
        <CollectionViewSource x:Key="cvs" Source="{Binding Source={StaticResource countries}}">
            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="Continent"/>
            </CollectionViewSource.GroupDescriptions>
        </CollectionViewSource>
        <DataTemplate x:Key="groupingHeaderTemplate">
            <Label VerticalAlignment="Center" Content="{Binding}" ></Label>
        </DataTemplate>
    </Window.Resources>

    <Grid>
        <ItemsControl ItemsSource="{Binding Source={StaticResource cvs}}" DisplayMemberPath="Name">
            <ItemsControl.GroupStyle>
                <GroupStyle HeaderTemplate= "{StaticResource groupingHeaderTemplate}" />
            </ItemsControl.GroupStyle>
        </ItemsControl>
    </Grid>
</Window>
//File:Window.xaml.cs
using System.Collections.ObjectModel;

namespace WpfApplication1
{
    public class Country
    {
        private string name;
        private Continent continent;

        public Country(string name, Continent continent)
        {
            this.name = name;
            this.continent = continent;
        }

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        public Continent Continent
        {
            get
            {
                return continent;
            }
            set
            {
                continent = value;
            }
        }
    }

    public enum Continent
    {
        Europe,
        NorthAmerica,
    }

    public class Countries : Collection<Country>
    {
        public Countries()
        {
            this.Add(new Country("Great Britan", Continent.Europe));
            this.Add(new Country("USA", Continent.NorthAmerica));
            this.Add(new Country("Canada", Continent.NorthAmerica));
        }
    }
}

   
    
     


Group Data in a Collection


   
  

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:WpfApplication1="clr-namespace:WpfApplication1"
     Title="WPF" Height="294" Width="160">
    <Window.Resources>
        <WpfApplication1:Countries x:Key="countries"/>
        <CollectionViewSource x:Key="cvs" Source="{Binding Source={StaticResource countries}}">
            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="Continent"/>
            </CollectionViewSource.GroupDescriptions>
        </CollectionViewSource>
        <DataTemplate x:Key="groupingHeaderTemplate">
            <Label VerticalAlignment="Center" Content="{Binding}" ></Label>
        </DataTemplate>
    </Window.Resources>

    <Grid>
        <ItemsControl ItemsSource="{Binding Source={StaticResource cvs}}" DisplayMemberPath="Name">
            <ItemsControl.GroupStyle>
                <GroupStyle HeaderTemplate= "{StaticResource groupingHeaderTemplate}" />
            </ItemsControl.GroupStyle>
        </ItemsControl>
    </Grid>
</Window>
//File:Window.xaml.cs
using System.Collections.ObjectModel;

namespace WpfApplication1
{
    public class Country
    {
        private string name;
        private Continent continent;

        public Country(string name, Continent continent)
        {
            this.name = name;
            this.continent = continent;
        }

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        public Continent Continent
        {
            get
            {
                return continent;
            }
            set
            {
                continent = value;
            }
        }
    }

    public enum Continent
    {
        Europe,
        NorthAmerica,
    }

    public class Countries : Collection<Country>
    {
        public Countries()
        {
            this.Add(new Country("Great Britan", Continent.Europe));
            this.Add(new Country("USA", Continent.NorthAmerica));
            this.Add(new Country("Canada", Continent.NorthAmerica));
        }
    }
}