Bind to a collection

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="Binding to a Collection"
  SizeToContent="WidthAndHeight">
  <Window.Resources>
    <local:People x:Key="MyFriends"/>
    <DataTemplate x:Key="DetailTemplate">
       <StackPanel>
          <TextBlock Text="First Name:"/>
          <TextBlock Text="{Binding Path=FirstName}"/>
          <TextBlock Text="Last Name:"/>
          <TextBlock Text="{Binding Path=LastName}"/>
      </StackPanel>
    </DataTemplate>
  </Window.Resources>
  <StackPanel>
    <TextBlock>My Friends:</TextBlock>
    <ListBox Width="200" IsSynchronizedWithCurrentItem="True"
             ItemsSource="{Binding Source={StaticResource MyFriends}}"/>
    <TextBlock>Information:</TextBlock>
    <ContentControl Content="{Binding Source={StaticResource MyFriends}}"
                    ContentTemplate="{StaticResource DetailTemplate}"/>
  </StackPanel>
</Window>
//File:Window.xaml.cs
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Data;
using System.Windows.Media;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace WpfApplication1
{    
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }
  public class Person : INotifyPropertyChanged
  {
      private string firstname;
      private string lastname;
      public event PropertyChangedEventHandler PropertyChanged;

      public Person()
      {
      }
      public Person(string first, string last)
      {
          this.firstname = first;
          this.lastname = last;
      }
      public override string ToString()
      {
          return firstname.ToString();
      }
      public string FirstName
      {
          get { return firstname; }
          set
          {
              firstname = value;
              OnPropertyChanged("FirstName");
          }
      }
      public string LastName
      {
          get { return lastname; }
          set
          {
              lastname = value;
              OnPropertyChanged("LastName");
          }
      }
      protected void OnPropertyChanged(string info)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
              handler(this, new PropertyChangedEventArgs(info));
          }
      }
  }
    public class People : ObservableCollection<Person>
    {
        public People(): base()
        {
            Add(new Person("A", "Q"));
            Add(new Person("B", "E"));
            Add(new Person("C", "E"));
            Add(new Person("D", "R"));
        }
    }
}

   
    
     


DataTemplate for binding

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="Binding to a Collection"
  SizeToContent="WidthAndHeight">
  <Window.Resources>
    <local:People x:Key="MyFriends"/>
    <DataTemplate x:Key="DetailTemplate">
       <StackPanel>
          <TextBlock Text="First Name:"/>
          <TextBlock Text="{Binding Path=FirstName}"/>
          <TextBlock Text="Last Name:"/>
          <TextBlock Text="{Binding Path=LastName}"/>
      </StackPanel>
    </DataTemplate>
  </Window.Resources>
  <StackPanel>
    <TextBlock>My Friends:</TextBlock>
    <ListBox Width="200" IsSynchronizedWithCurrentItem="True"
             ItemsSource="{Binding Source={StaticResource MyFriends}}"/>
    <TextBlock>Information:</TextBlock>
    <ContentControl Content="{Binding Source={StaticResource MyFriends}}"
                    ContentTemplate="{StaticResource DetailTemplate}"/>
  </StackPanel>
</Window>
//File:Window.xaml.cs
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Data;
using System.Windows.Media;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace WpfApplication1
{    
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }
  public class Person : INotifyPropertyChanged
  {
      private string firstname;
      private string lastname;
      public event PropertyChangedEventHandler PropertyChanged;

      public Person()
      {
      }
      public Person(string first, string last)
      {
          this.firstname = first;
          this.lastname = last;
      }
      public override string ToString()
      {
          return firstname.ToString();
      }
      public string FirstName
      {
          get { return firstname; }
          set
          {
              firstname = value;
              OnPropertyChanged("FirstName");
          }
      }
      public string LastName
      {
          get { return lastname; }
          set
          {
              lastname = value;
              OnPropertyChanged("LastName");
          }
      }
      protected void OnPropertyChanged(string info)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
              handler(this, new PropertyChangedEventArgs(info));
          }
      }
  }
    public class People : ObservableCollection<Person>
    {
        public People(): base()
        {
            Add(new Person("A", "Q"));
            Add(new Person("B", "E"));
            Add(new Person("C", "E"));
            Add(new Person("D", "R"));
        }
    }
}

   
    
     


Binding Environment Info

image_pdfimage_print


   
  
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        xmlns:src="clr-namespace:MyNameSpace.EnvironmentInfo2" 
        Title="Environment Info">
    <Window.Resources>
        <src:FormattedMultiTextConverter x:Key="conv" />
    </Window.Resources>

    <TextBlock>
        <TextBlock.Text>
            <MultiBinding Converter="{StaticResource conv}"
                          ConverterParameter=
"Operating System Version: {0}
&amp;#x000A;.NET Version: {1}
&amp;#x000A;Machine Name: {2}
&amp;#x000A;User Name: {3}" >
                <Binding Source="{x:Static s:Environment.OSVersion}" />
                <Binding Source="{x:Static s:Environment.Version}" />
                <Binding Source="{x:Static s:Environment.MachineName}" />
                <Binding Source="{x:Static s:Environment.UserName}" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</Window>
//File:Window.xaml.cs
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace MyNameSpace.EnvironmentInfo2
{
    public class FormattedMultiTextConverter : IMultiValueConverter
    {
        public object Convert(object[] value, Type typeTarget, 
                              object param, CultureInfo culture)
        {
            return String.Format((string) param, value);
        }
        public object[] ConvertBack(object value, Type[] typeTarget, 
                                    object param, CultureInfo culture)
        {
            return null;
        }
    }
}

   
    
     


Bind to an ADO.NETDataSet

image_pdfimage_print






















//File:Window.xaml.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Collections.Generic;

namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
this.InitializeComponent();
}
DataSet myDataSet;
private void OnInit(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(“Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:BookData.mdb”);
OleDbDataAdapter adapter = new OleDbDataAdapter(“SELECT * FROM BookTable;”, conn);

myDataSet = new DataSet();
adapter.Fill(myDataSet, “BookTable”);

myListBox.DataContext = myDataSet;
}
private void OnClick(object sender, RoutedEventArgs e)
{
DataTable myDataTable = myDataSet.Tables[“BookTable”];
DataRow row = myDataTable.NewRow();

row[“Title”] = “A”;
row[“ISBN”] = “0-1111-1111-2”;
row[“NumPages”] = 1;
myDataTable.Rows.Add(row);
}
}
public class IntColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int numValue = (int)value;
if (numValue < 50) return System.Windows.Media.Brushes.Green; else return System.Windows.Media.Brushes.Red; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } } [/csharp]

Add a value converter to a binding using XAML

image_pdfimage_print


   
  


<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:c="clr-namespace:WpfApplication1" Width="300" Height="300"
  Name="Page1">
  <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>
//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 WpfApplication1
{
  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);
            case "Brush":
                return Brushes.Red;
            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));
      }
    }
  }
}

   
    
     


Custom Dialog with data binding

image_pdfimage_print
   
  

<Window x:Class="CustomDialogSample.SettingsDialog"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Settings"
  Height="200"
  Width="400"
  ResizeMode="CanResizeWithGrip"
  SizeToContent="WidthAndHeight"
  WindowStartupLocation="CenterOwner"
  FocusManager.FocusedElement="{Binding ElementName=myStringTextBox}"
  ShowInTaskbar="False">

  <StackPanel>
    <Label Target="{Binding ElementName=myStringTextBox}">Report _Folder</Label>
    <TextBox x:Name="myStringTextBox" Text="{Binding MyString}" />
    <Button x:Name="folderBrowseButton">...</Button>
    <Button HorizontalAlignment="Left" Name="reportColorButton">
       <StackPanel>
      <Rectangle Width="15" Height="15" SnapsToDevicePixels="True"
                   Fill="{StaticResource reportBrush}" />
        <AccessText Text="Report _Color..." Margin="10,0,0,0" />
      </StackPanel>
    </Button>
    <Button x:Name="okButton" IsDefault="True">OK</Button>
    <Button x:Name="cancelButton" IsCancel="True">Cancel</Button>
  </StackPanel>
</Window>
//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;


namespace CustomDialogSample {
    class DialogData : INotifyPropertyChanged {
      Color reportColor;
      public Color MyColor {
        get { return reportColor; }
        set { reportColor = value; Notify("MyColor"); }
      }

      string mystring;
      public string MyString {
        get { return mystring; }
        set { mystring = value; Notify("MyString"); }
      }

      public event PropertyChangedEventHandler PropertyChanged;
      void Notify(string prop) { if( PropertyChanged != null ) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); } }
    }
  public partial class SettingsDialog : System.Windows.Window {
    DialogData data = new DialogData();

    public Color MyColor {
      get { return data.MyColor; }
      set { data.MyColor = value; }
    }

    public string MyString {
      get { return data.MyString; }
      set { data.MyString = value; }
    }

    public SettingsDialog() {
      InitializeComponent();

      DataContext = data;

      reportColorButton.Click += reportColorButton_Click;
      folderBrowseButton.Click += folderBrowseButton_Click;
      okButton.Click += new RoutedEventHandler(okButton_Click);
    }

    void okButton_Click(object sender, RoutedEventArgs e) {
      DialogResult = true;
    }
    void reportColorButton_Click(object sender, RoutedEventArgs e) {
      System.Windows.Forms.ColorDialog dlg = new System.Windows.Forms.ColorDialog();
      Color color = MyColor;
      dlg.Color = System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B);

      if( dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK ) {
        MyColor = Color.FromArgb(dlg.Color.A, dlg.Color.R, dlg.Color.G, dlg.Color.B);
      }
    }

    void folderBrowseButton_Click(object sender, RoutedEventArgs e) {
      System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
      dlg.SelectedPath = MyString;
      if( dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK ) {
        MyString = dlg.SelectedPath;
      }
    }

  }
}

   
    
     


One way and two way binding

image_pdfimage_print


   
  

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:MyNameSpace.CustomElementBinding" 
        Title="Custom Element Binding Demo">
    <StackPanel>
    <ScrollBar Name="scroll"
               Orientation="Horizontal"
               Margin="24" 
               Maximum="100"
               LargeChange="10"
               SmallChange="1" 
               Value="{Binding ElementName=simple, Path=Number,Mode=TwoWay}" />
    <src:SimpleElement Number="{Binding ElementName=scroll,Path=Value,Mode=OneWay}"/>
    </StackPanel>
</Window>
//File:Window.xaml.cs
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media;

namespace MyNameSpace.CustomElementBinding
{
    class SimpleElement : FrameworkElement
    {
        public static DependencyProperty NumberProperty;
        static SimpleElement()
        {
            NumberProperty = DependencyProperty.Register("Number", typeof(double),typeof(SimpleElement),
                    new FrameworkPropertyMetadata(0.0,FrameworkPropertyMetadataOptions.AffectsRender));
        }
        public double Number
        {
            set { SetValue(NumberProperty, value); }
            get { return (double)GetValue(NumberProperty); }
        }
        protected override Size MeasureOverride(Size sizeAvailable)
        {
            return new Size(200, 250);
        }
        protected override void OnRender(DrawingContext dc)    
        {
            dc.DrawText(new FormattedText(Number.ToString(), 
                        CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                        new Typeface("Times New Roman"), 12, 
                        SystemColors.WindowTextBrush),new Point(0, 0)); 
        }
    }
}