Object Binding : Binding « Windows Presentation Foundation « C# / CSharp Tutorial






<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"
  xmlns:sys="clr-namespace:System;assembly=mscorlib"
  Title="ListBinding" Height="325" Width="400">
  <Window.Resources>
    <ObjectDataProvider x:Key="Family" ObjectType="{x:Type local:RemoteEmployeesLoader}"
      IsAsynchronous="True" MethodName="LoadEmployees">
      <ObjectDataProvider.MethodParameters>
        <sys:String>http://host/d.dat</sys:String>
        <sys:String>http://host/d2.dat</sys:String>
      </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>

    <local:AgeToForegroundConverter x:Key="ageConverter" />
    <DataTemplate DataType="{x:Type local:Employee}">
      <TextBlock>
        <TextBlock Text="{Binding Path=Name}" />
        (age: <TextBlock Text="{Binding Path=Age}" Foreground="{Binding Path=Age, Converter={StaticResource ageConverter}}" />)
      </TextBlock>
    </DataTemplate>
  </Window.Resources>
  <StackPanel DataContext="{StaticResource Family}">
    <ListBox ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True">
      <ListBox.GroupStyle>
        <x:Static Member="GroupStyle.Default" />
      </ListBox.GroupStyle>
    </ListBox>

    <TextBlock>Name:</TextBlock>
    <TextBox Text="{Binding Path=Name}" />
    <TextBlock>Age:</TextBlock>
    <TextBox Text="{Binding Path=Age}" Foreground="{Binding Path=Age, Converter={StaticResource ageConverter}}" />
      <Button Name="birthdayButton">Birthday</Button>
      <Button Name="backButton">&lt;</Button>
      <Button Name="forwardButton">&gt;</Button>
      <Button Name="addButton">Add</Button>
      <Button Name="sortButton">Sort</Button>
      <Button Name="filterButton">Filter</Button>
      <Button Name="groupButton">Group</Button>
  </StackPanel>
</Window>

//File:Window.xaml.cs

using System;
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.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel; 
using System.Collections.ObjectModel;
using System.Collections;

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 {
        this.name = value;
        Notify("Name");
      }
    }

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

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

  public class Employees : ObservableCollection<Employee> { }

  public class RemoteEmployeesLoader {
    public Employees LoadEmployees(string url1, string url2) {
      Employees employees = new Employees();
      employees.Add(new Employee("A", 31));
      employees.Add(new Employee("B", 42));
      employees.Add(new Employee("C", 68));
      return employees;
    }
  }

  public partial class Window1 : Window {

    public Window1() {
      InitializeComponent();

      this.birthdayButton.Click += birthdayButton_Click;
      this.backButton.Click += backButton_Click;
      this.forwardButton.Click += forwardButton_Click;
      this.addButton.Click += addButton_Click;
      this.sortButton.Click += sortButton_Click;
      this.filterButton.Click += filterButton_Click;
      this.groupButton.Click += groupButton_Click;
    }

    ICollectionView GetFamilyView() {
      DataSourceProvider provider = (DataSourceProvider)this.FindResource("Family");
      Employees employees = (Employees)provider.Data;
      return CollectionViewSource.GetDefaultView(employees);
    }

    void birthdayButton_Click(object sender, RoutedEventArgs e) {
      ICollectionView view = GetFamilyView();
      Employee person = (Employee)view.CurrentItem;

      ++person.Age;
      Console.WriteLine(person.Name);
      Console.WriteLine(person.Age);
    }

    void backButton_Click(object sender, RoutedEventArgs e) {
      ICollectionView view = GetFamilyView();
      view.MoveCurrentToPrevious();
      if( view.IsCurrentBeforeFirst ) {
        view.MoveCurrentToFirst();
      }
    }

    void forwardButton_Click(object sender, RoutedEventArgs e) {
      ICollectionView view = GetFamilyView();
      view.MoveCurrentToNext();
      if( view.IsCurrentAfterLast ) {
        view.MoveCurrentToLast();
      }
    }

    void addButton_Click(object sender, RoutedEventArgs e) {
      DataSourceProvider provider = (DataSourceProvider)this.FindResource("Family");
      Employees employees = (Employees)provider.Data;
      employees.Add(new Employee("EE", 67));
    }

    class EmployeeSorter : IComparer {
      public int Compare(object x, object y) {
        Employee lhs = (Employee)x;
        Employee rhs = (Employee)y;

        int nameCompare = lhs.Name.CompareTo(rhs.Name);
        if( nameCompare != 0 )
          return nameCompare;
        return rhs.Age - lhs.Age;
      }
    }

    void sortButton_Click(object sender, RoutedEventArgs e) {
      ListCollectionView view = (ListCollectionView)GetFamilyView();
      if( view.CustomSort == null ) {
        view.CustomSort = new EmployeeSorter();
      }
      else {
        view.CustomSort = null;
      }
    }

    void filterButton_Click(object sender, RoutedEventArgs e) {
      ICollectionView view = GetFamilyView();
      if( view.Filter == null ) {
        view.Filter = delegate(object item) {
          return ((Employee)item).Age >= 25;
        };
      }
      else {
        view.Filter = null;
      }
    }

    void groupButton_Click(object sender, RoutedEventArgs e) {
      ICollectionView view = GetFamilyView();
      if( view.GroupDescriptions.Count == 0 ) {
        view.GroupDescriptions.Add(new PropertyGroupDescription("Age"));
      }
      else {
        view.GroupDescriptions.Clear();
      }
    }

  }

  public class AgeToForegroundConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
      Debug.Assert(targetType == typeof(Brush));

      int age = int.Parse(value.ToString());
      return (age > 25 ? Brushes.Red : Brushes.Black);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
      throw new NotImplementedException();
    }
  }

}
WPF Object Binding








24.129.Binding
24.129.1.Bind to Window itselfBind to Window itself
24.129.2.Two level path bindingTwo level path binding
24.129.3.Bind RelativeSource's AncestorTypeBind RelativeSource's AncestorType
24.129.4.Bind RelativeSource's AncestorType's PathBind RelativeSource's AncestorType's Path
24.129.5.Bind Stroke Thickness to SliderBind Stroke Thickness to Slider
24.129.6.Desktop to ControlDesktop to Control
24.129.7.Binding With Data ContextBinding With Data Context
24.129.8.Long Binding PathLong Binding Path
24.129.9.Bind ListBox ItemsSource to DayNames property of DateTimeFormatInfoBind ListBox ItemsSource to DayNames property of DateTimeFormatInfo
24.129.10.Bind TextBlock Text to SelectedItem property of ListBoxBind TextBlock Text to SelectedItem property of ListBox
24.129.11.Binding FontFamily / FontSize value for current ControlBinding FontFamily / FontSize value for current Control
24.129.12.Bind to IDataErrorInfoBind to IDataErrorInfo
24.129.13.DataTemplate for bindingDataTemplate for binding
24.129.14.Binding Environment InfoBinding Environment Info
24.129.15.Bind to an ADO.NETDataSetBind to an ADO.NETDataSet
24.129.16.Add a value converter to a binding using XAMLAdd a value converter to a binding using XAML
24.129.17.Custom Dialog with data bindingCustom Dialog with data binding
24.129.18.One way and two way bindingOne way and two way binding
24.129.19.Object BindingObject Binding
24.129.20.Without BindingWithout Binding
24.129.21.Master Detail BindingMaster Detail Binding
24.129.22.Data binding using collections composed of mixed types of data.Data binding using collections composed of mixed types of data.
24.129.23.List BindingList Binding
24.129.24.Async bindingAsync binding
24.129.25.Hierarchical Binding for three level nested objectsHierarchical Binding for three level nested objects
24.129.26.BindingOperations.GetBindingExpressionBindingOperations.GetBindingExpression
24.129.27.Bind to enum typesBind to enum types
24.129.28.Bind to a MethodBind to a Method
24.129.29.Bind an ItemsControl to the CollectionViewSource, Set its DisplayMemberPath to display the Name propertyBind an ItemsControl to the CollectionViewSource, Set its DisplayMemberPath to display the Name property
24.129.30.Bind to the Values of an EnumerationBind to the Values of an Enumeration
24.129.31.Bind to an Existing Object InstanceBind to an Existing Object Instance
24.129.32.Digital ClockDigital Clock
24.129.33.Formatted Digital ClockFormatted Digital Clock
24.129.34.Manual Update TargetManual Update Target