<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; } } } }
Author: coder
One way and two way binding
<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)); } } }
Object Binding
<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(); } } }
Without Binding
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="WithoutBinding" Height="135" Width="200"> <StackPanel> <TextBlock>Name:</TextBlock> <TextBox Name="nameTextBox"/> <TextBlock>Age:</TextBlock> <TextBox Name="ageTextBox"/> <Button Name="birthdayButton">Birthday</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 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 partial class Window1 : Window { Employee emp = new Employee("Tom", 11); public Window1() { InitializeComponent(); this.nameTextBox.Text = emp.Name; this.ageTextBox.Text = emp.Age.ToString(); emp.PropertyChanged += emp_PropertyChanged; this.nameTextBox.TextChanged += nameTextBox_TextChanged; this.ageTextBox.TextChanged += ageTextBox_TextChanged; this.birthdayButton.Click += birthdayButton_Click; } void emp_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch( e.PropertyName ) { case "Name": this.nameTextBox.Text = emp.Name; break; case "Age": this.ageTextBox.Text = emp.Age.ToString(); break; } } void nameTextBox_TextChanged(object sender, TextChangedEventArgs e) { emp.Name = nameTextBox.Text; } void ageTextBox_TextChanged(object sender, TextChangedEventArgs e) { int age = 0; if( int.TryParse(ageTextBox.Text, out age) ) { emp.Age = age; } } void birthdayButton_Click(object sender, RoutedEventArgs e) { ++emp.Age; Console.WriteLine(emp.Name); Console.WriteLine(emp.Age); } } }
Master Detail Binding
<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MasterDetailBinding" xmlns:local="clr-namespace:WpfApplication1"> <Window.Resources> <local:Companies x:Key="Companies"> <local:Company CompanyName="Stooge"> <local:Company.Members> <local:Team> <local:Employee Name="Larry" Age="21"> <local:Employee.Skills> <local:Skills> <local:Skill Description="A" /> <local:Skill Description="B" /> <local:Skill Description="C" /> </local:Skills> </local:Employee.Skills> </local:Employee> <local:Employee Name="Moe" Age="22" > <local:Employee.Skills> <local:Skills> <local:Skill Description="D" /> <local:Skill Description="E" /> </local:Skills> </local:Employee.Skills> </local:Employee> <local:Employee Name="Curly" Age="23" > <local:Employee.Skills> <local:Skills> <local:Skill Description="F" /> <local:Skill Description="G" /> </local:Skills> </local:Employee.Skills> </local:Employee> </local:Team> </local:Company.Members> </local:Company> <local:Company CompanyName="Addams"> <local:Company.Members> <local:Team> <local:Employee Name="Gomez" Age="135" > <local:Employee.Skills> <local:Skills> <local:Skill Description="H" /> <local:Skill Description="Z" /> <local:Skill Description="Q" /> </local:Skills> </local:Employee.Skills> </local:Employee> <local:Employee Name="Morticia" Age="121" > <local:Employee.Skills> <local:Skills> <local:Skill Description="R" /> <local:Skill Description="P" /> <local:Skill Description="L" /> </local:Skills> </local:Employee.Skills> </local:Employee> <local:Employee Name="Fester" Age="137" > <local:Employee.Skills> <local:Skills> <local:Skill Description="R" /> <local:Skill Description="S" /> <local:Skill Description="U" /> </local:Skills> </local:Employee.Skills> </local:Employee> </local:Team> </local:Company.Members> </local:Company> </local:Companies> </Window.Resources> <Grid DataContext="{StaticResource Companies}"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="0">Companies:</TextBlock> <ListBox Grid.Row="1" Grid.Column="0" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Path=CompanyName}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <StackPanel Grid.Row="0" Grid.Column="1" Orientation="Horizontal"> <TextBlock Text="{Binding Path=CompanyName}" /> <TextBlock Text=" Company Members:" /> </StackPanel> <ListBox Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Path=Members}" IsSynchronizedWithCurrentItem="True"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock> <TextBlock Text="{Binding Path=Name}" /> (age: <TextBlock Text="{Binding Path=Age}" />) </TextBlock> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <StackPanel Grid.Row="0" Grid.Column="2" Orientation="Horizontal"> <TextBlock Text="{Binding Path=Members/Name}" /> <TextBlock Text=" Skills:" /> </StackPanel> <ListBox Grid.Row="1" Grid.Column="2" ItemsSource="{Binding Path=Members/Skills}" IsSynchronizedWithCurrentItem="True"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Path=Description}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> //File:Window.xaml.cs using System; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Shapes; using System.Collections.ObjectModel; namespace WpfApplication1 { public class Skill { string description; public string Description { get { return description; } set { description = value; } } } public class Skills : ObservableCollection<Skill> { } public class Employee { string name; public string Name { get { return name; } set { name = value; } } int age; public int Age { get { return age; } set { age = value; } } Skills traits; public Skills Skills { get { return traits; } set { traits = value; } } } public class Team : ObservableCollection<Employee> { } public class Company { string familyName; public string CompanyName { get { return familyName; } set { familyName = value; } } Team members; public Team Members { get { return members; } set { members = value; } } } public class Companies : ObservableCollection<Company> { } public partial class Window1 : Window { public Window1() { InitializeComponent(); } } }
Data binding using collections composed of mixed types of data.
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:c="clr-namespace:WpfApplication1" x:Class="WpfApplication1.Window1" Title="CompositeCollections" SizeToContent="WidthAndHeight"> <Window.Resources> <c:Employees x:Key="EmployeesData"/> <XmlDataProvider x:Key="NewStudentesData" XPath="NewStudentes/Student"> <x:XData> <NewStudentes xmlns=""> <Student Name="Jason" /> <Student Name="Hercules" /> <Student Name="Bellerophon" /> <Student Name="Theseus" /> <Student Name="Odysseus" /> <Student Name="Perseus" /> </NewStudentes> </x:XData> </XmlDataProvider> <DataTemplate DataType="{x:Type c:Employee}"> <TextBlock Text="{Binding Path=Name}" Foreground="Gold"/> </DataTemplate> <DataTemplate DataType="Student"> <TextBlock Text="{Binding XPath=@Name}" Foreground="Cyan"/> </DataTemplate> </Window.Resources> <StackPanel> <ListBox Name="myListBox" Height="300" Width="200"> <ListBox.ItemsSource> <CompositeCollection> <CollectionContainer Collection="{Binding Source={StaticResource EmployeesData}}" /> <CollectionContainer Collection="{Binding Source={StaticResource NewStudentesData}}" /> <ListBoxItem Foreground="Red">Other Listbox Item 1</ListBoxItem> </CompositeCollection> </ListBox.ItemsSource> </ListBox> </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.Navigation; using System.Windows.Shapes; using System.Windows.Data; using System.Collections.ObjectModel; namespace WpfApplication1 { public partial class Window1 : Window { public Window1() { InitializeComponent(); } } public class Employee { private string _name; public string Name { get { return _name; } set { _name = value; } } public Employee(string name) { Name = name; } } public class Employees : ObservableCollection<Employee> { public Employees() { Add(new Employee("A")); Add(new Employee("B")); Add(new Employee("C")); } } }
Text Data Binding
<Window x:Class="TextDataBinding.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="TextDataBinding" Height="300" Width="300"> <Grid> <TextBlock> Name: <TextBlock Text="{Binding FirstName}" /> <TextBlock Text="{Binding LastName}" /> </TextBlock> </Grid> </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; namespace TextDataBinding { public partial class Window1 : System.Windows.Window { Person src = new Person(); public Window1() { InitializeComponent(); src.FirstName = "A"; src.LastName = "B"; this.DataContext = src; } } public class Person { private string firstNameValue; public string FirstName { get { return firstNameValue; } set { firstNameValue = value; } } private string lastNameValue; public string LastName { get { return lastNameValue; } set { lastNameValue = value; } } } }