目录
2)普通CLR对象(实现INotifyPropertyChanged接口)
1)没有Path的绑定(绑定源本身是数据且不需要Path来指明)
2)Path是"."(绑定源本身是数据且不需要Path来指明)
Binding源(Source)
Binding.Source:获取或设置要用作绑定源的对象。
XAML 属性用法
<object Source="object"/>
object
现有的对象。 若要引用现有对象,请使用 StaticResource 标记扩展
Binding来源
数据来源 | 举例 | 备注 |
---|---|---|
普通的CLR对象 | 自带类型和用户自定义 | 类实现INotifyPropertyChanged接口,set语句中激发PropertyChanged事件通知Binding数据已被更新 |
普通CLR集合对象 | ObjectCollection<T>、List<T> | 一般把控件的ItemsSource属性使用Binding关联到一个集合对象上。 |
ADO.NET数据 | DataTable、DataView等 | |
XmlDataProvider | 级联式控件,如TreeView,Menu | |
依赖对象 | 可以作为绑定目标和绑定源,也可以形成绑定链 | |
DataContext | 不指定Source,指定Path。 | |
ElementName | C#需要RegisterName注册Name | |
RelativeSource | 控件关注自己的、自己容器的或自己的内部元素的某个值就需要使用这种办法。 | |
ObjectDataProvider | 当数据源的数据不是通过属性而是通过方法暴露给外界的时候使用 | |
LINQ |
1)控件作为源(依赖对象)
语法:
<UIElement x:Name="UIElementName" Property="{Binding Path=_Path,ElementName="_UIelementName" }"/>
UIElementName.SetBinding(UIElement.Property, new Binding("_Path"){ElementName="_UIelementName"});
BindingOperations.SetBinding(UIElementName, UIElement.Property, new Binding("_Path"){ElementName="_UIelementName"});
范例:
XAML范例
<Window x:Class="BindingDemo2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingDemo2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<TextBlock x:Name="tbk1" Text="{Binding Path=Value,ElementName=sld1}"/>
<Slider x:Name="sld1" Maximum="100"/>
</StackPanel>
</Window>
C#范例一
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TextBlock tbk1 = new TextBlock();
Slider sld1 = new Slider { Maximum = 100, Name = "sld1" };
RegisterName(sld1.Name, sld1);
StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(tbk1);
stackPanel.Children.Add(sld1);
this.Content = stackPanel;
//方法①
//BindingOperations.SetBinding(tbk1, TextBlock.TextProperty, new Binding("Value") { ElementName = "sld1" });
//方法②
tbk1.SetBinding(TextBlock.TextProperty, new Binding("Value") { ElementName = "sld1" });
}
}
XAML和C#范例
<Window x:Class="BindingDemo2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingDemo2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel>
<TextBlock x:Name="tbk1" />
<Slider x:Name="sld1" Maximum="100"/>
</StackPanel>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//方法①
//BindingOperations.SetBinding(tbk1, TextBlock.TextProperty, new Binding("Value") { ElementName = "sld1" });
//方法②
tbk1.SetBinding(TextBlock.TextProperty, new Binding("Value") { ElementName = "sld1" });
}
}
C#范例二
public MainWindow()
{
InitializeComponent();
TextBlock tbk1 = new TextBlock();
Slider sld1 = new Slider { Maximum = 100 };
StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(tbk1);
stackPanel.Children.Add(sld1);
this.Content = stackPanel;
//方法①
BindingOperations.SetBinding(tbk1, TextBlock.TextProperty, new Binding() { Source = sld1,Path=new PropertyPath("Value") });
//方法②
//tbk1.SetBinding(TextBlock.TextProperty, new Binding() { Source = sld1, Path = new PropertyPath("Value") } );
}
2)普通CLR对象(实现INotifyPropertyChanged接口)
<Window x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<StackPanel>
<TextBox x:Name="tbx1"/>
<Button Content="改变Number" Click="OnClick"/>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace BindingSourceDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
Number number = new Number();
public MainWindow()
{
InitializeComponent();
number.ANumber = 5;
tbx1.SetBinding(TextBox.TextProperty, new Binding { Path =new PropertyPath("ANumber"), Source= number }) ;
}
public class Number : System.ComponentModel.INotifyPropertyChanged
{
private int aNumber;
public int ANumber
{
get { return aNumber; }
set
{
aNumber = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("ANumber"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
private void OnClick(object sender, RoutedEventArgs e)
{
number.ANumber = 10;
}
}
}
3)普通CLR集合对象
- ItemsSource
- DisplayMemberPath
C#范例
<Window x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<StackPanel>
<ListBox x:Name="ltx1"/>
<TextBlock x:Name="tbk1"/>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace BindingSourceDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Student> students = new List<Student> {
new Student(){School="浙大",Class=106,Name="张瑞阳" },
new Student(){School="电大",Class=303,Name="王芳" },
new Student(){School="科大",Class=107,Name="李玉华" },
new Student(){School="浙大",Class=403,Name="黄天涯" },
new Student(){School="电大",Class=209,Name="叶丈竹" },
};
ltx1.ItemsSource = students;
ltx1.DisplayMemberPath = "Name";
tbk1.SetBinding(TextBlock.TextProperty,new Binding("SelectedItem.Class") { Source= ltx1 });
}
public class Student
{
public string Name { get; set; }
public int Class { get; set; }
public string School { get; set; }
}
}
}
XAML范例
<Window x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:clc= "clr-namespace:System.Collections.Generic;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<Window.Resources>
<local:students x:Key="mystudents"/>
</Window.Resources>
<StackPanel>
<ListBox x:Name="ltx1" ItemsSource="{StaticResource mystudents }" DisplayMemberPath="Name"/>
<TextBlock x:Name="tbk1" Text="{Binding Path=SelectedItem.Class, ElementName=ltx1}"/>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace BindingSourceDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class Student
{
public string Name { get; set; }
public int Class { get; set; }
public string School { get; set; }
}
public class students : System.Collections.ObjectModel.ObservableCollection<Student>
{
public students()
{
Add(new Student() { School = "浙大", Class = 106, Name = "张瑞阳" });
Add(new Student(){School="电大",Class=303,Name="王芳" });
Add(new Student(){School="科大",Class=107,Name="李玉华" });
Add(new Student(){School="浙大",Class=403,Name="黄天涯" });
Add(new Student(){School="电大",Class=209,Name="叶丈竹" });
}
}
}
4)ADO.NET数据
<Window x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:clc= "clr-namespace:System.Collections.Generic;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="330" Width="400">
<StackPanel>
<ListView x:Name="lvW1" >
<ListView.View>
<GridView>
<GridViewColumn Header="ChildID" DisplayMemberBinding="{Binding ChildID}"/>
<GridViewColumn Header="ChildItem" DisplayMemberBinding="{Binding ChildItem}"/>
<GridViewColumn Header="ParentID" DisplayMemberBinding="{Binding ParentID}"/>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace BindingSourceDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataTable dataTable = new DataTable("myTable");
GetData(dataTable);
lvW1.ItemsSource = dataTable.DefaultView;
lvW1.DisplayMemberPath = "ChildItem";
}
private void GetData(DataTable table)
{
DataColumn column;
DataRow row;
// Create first column and add to the DataTable.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ChildID";
column.AutoIncrement = false;
column.Caption = "ID";
column.ReadOnly = false;
column.Unique = false;
// Add the column to the DataColumnCollection.
table.Columns.Add(column);
// Create second column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ChildItem";
column.AutoIncrement = false;
column.Caption = "ChildItem";
column.ReadOnly = false;
column.Unique = false;
table.Columns.Add(column);
// Create third column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ParentID";
column.AutoIncrement = false;
column.Caption = "ParentID";
column.ReadOnly = false;
column.Unique = false;
table.Columns.Add(column);
// Create three sets of DataRow objects,
// five rows each, and add to DataTable.
for (int i = 0; i <= 4; i++)
{
row = table.NewRow();
row["childID"] = "childID "+i.ToString();
row["ChildItem"] = "ChildItem " + i.ToString();
row["ParentID"] = "ParentID 0";
table.Rows.Add(row);
}
for (int i = 0; i <= 4; i++)
{
row = table.NewRow();
row["childID"] = "childID " + (i+5).ToString();
row["ChildItem"] = "ChildItem " + i.ToString();
row["ParentID"] = "ParentID 1";
table.Rows.Add(row);
}
for (int i = 0; i <= 4; i++)
{
row = table.NewRow();
row["childID"] = "childID " + (i + 10).ToString();
row["ChildItem"] = "ChildItem " + i.ToString();
row["ParentID"] = "ParentID 2";
table.Rows.Add(row);
}
}
}
}
5)XmlDataProvider
Object->DataSourceProvider->XmlDataProvider
允许以声明方式访问数据绑定的 XML 数据。
名称 | 备注 | 权限 |
---|---|---|
此类型或成员支持 WPF 基础结构,不应在代码中直接使用。 | get; set; | |
获取或设置要用作绑定源的 XmlDocument。 | get; set; | |
获取或设置一个值,该值指示是在辅助线程还是在活动上下文中执行节点集合创建。 | get; set; | |
获取或设置 Uri 要用作绑定源的 XML 数据文件的。 | get; set; | |
获取或设置用于运行 XmlNamespaceManager 查询的 XPath。 | get; set; | |
获取内联 XML 内容。 | get; | |
获取或设置用于生成数据集合的 XPath 查询。 | get; set; |
名称 | 备注 | 权限 |
---|---|---|
准备加载内联 XML 或外部 XML 文件以生成 XML 节点的集合。 | protected | |
表示此元素的初始化已完成。如果没有其他未完成的 Refresh(),则这会导致 DeferRefresh()。 | protected | |
指示是否应使 Source 属性持久化。 | public | |
指示是否应使 XmlSerializer 属性持久化。 | public | |
指示是否应使 XPath 属性持久化。 | public |
名称 | 备注 |
---|---|
Uri System.Windows.Markup.IUriContext.BaseUri { get; set; } |
<Window x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingSourceDemo"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<StackPanel>
<ListView x:Name="lvw1" >
<ListView.View>
<GridView>
<GridViewColumn Header="ID" Width="150" DisplayMemberBinding="{Binding XPath=@Id}"/>
<GridViewColumn Header="Name" Width="200" DisplayMemberBinding="{Binding XPath=Name}"/>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Xml;
namespace BindingSourceDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
XmlLoad();
}
private void XmlLoad()
{
XmlDataProvider xmlDataProvider = new XmlDataProvider();
//1
//XmlDocument xmlDocument = new XmlDocument();
//xmlDocument.Load(@"G:\c#\WPF深入浅出\BindingSourceDemo\myXML.xml");
//xmlDataProvider.Document = xmlDocument;
//2
xmlDataProvider.Source = new Uri(@"G:\c#\WPF深入浅出\BindingSourceDemo\myXML.xml");
xmlDataProvider.XPath = @"/StudentList/Student";
lvw1.DataContext = xmlDataProvider;
lvw1.SetBinding(ListView.ItemsSourceProperty,new Binding());
}
}
}
Window.Resources作为数据源
<Window x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingSourceDemo"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<Window.Resources>
<XmlDataProvider x:Key="xdp" XPath="FileSystem/Folder">
<x:XData>
<FileSystem xmlns="">
<Folder Name="Books">
<Folder Name="Programming">
<Folder Name="Windows">
<Folder Name="WPF"/>
<Folder Name="MFC"/>
<Folder Name="Delphi"/>
</Folder>
<Folder Name="Tools">
<Folder Name="Develoment"/>
<Folder Name="Designment"/>
<Folder Name="Players"/>
</Folder>
</Folder>
</Folder>
</FileSystem>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<StackPanel>
<TreeView ItemsSource="{Binding Source={StaticResource xdp}}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding XPath=Folder}">
<TextBlock Text="{Binding XPath=@Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Xml;
namespace BindingSourceDemo
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//XmlLoad();
}
}
}
6)DataContext
- 没有Source
- 沿着UI树一路向树根找过去
XAML范例
<Window x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:clc= "clr-namespace:System.Collections.Generic;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<Window.DataContext>
<local:Student School = "浙大" Class = "106" Name = "张瑞阳" />
</Window.DataContext>
<StackPanel>
<TextBlock x:Name="tbk1" Text="{Binding Path=Name}"/>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace BindingSourceDemo
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class Student
{
public string Name { get; set; }
public int Class { get; set; }
public string School { get; set; }
}
}
C#范例
<Window x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:clc= "clr-namespace:System.Collections.Generic;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
</Window>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace BindingSourceDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Student student = new Student { School = "浙大", Class = 106, Name = "张瑞阳" };
this.DataContext = student;
StackPanel stackPanel = new StackPanel();
TextBlock textBlock = new TextBlock();
stackPanel.Children.Add(textBlock);
this.Content = stackPanel;
textBlock.SetBinding(TextBlock.TextProperty, new Binding("Name") );
}
public class Student
{
public string Name { get; set; }
public int Class { get; set; }
public string School { get; set; }
}
}
}
没有Source、没有Path的范例
Source本身是数据,Path可以不设置。
<Window x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:clc= "clr-namespace:System.Collections.Generic;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<Window.DataContext>
<sys:String >This is Window.DataContext</sys:String>
</Window.DataContext>
<StackPanel>
<TextBlock x:Name="tbk1" Text="{Binding}"/>
</StackPanel>
</Window>
7)ElementName
获取或设置要用作绑定源对象的元素的名称。
XAML范例
<Window
x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:collection="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow"
Width="400"
Height="200"
mc:Ignorable="d">
<StackPanel Orientation="Vertical">
<TextBox Text="ElementName Demo" x:Name="tbx1"/>
<TextBox Text="{Binding Path=Text ,ElementName=tbx1}" />
</StackPanel>
</Window>
C#范例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Xml;
namespace BindingSourceDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
StackPanel stackPanel = new StackPanel();
TextBox textBox1 = new TextBox { Text = "ElementName Demo", Name = "tbx1" };
TextBox textBox2 = new TextBox();
RegisterName("tbx1", textBox1);
stackPanel.Children.Add(textBox1);
stackPanel.Children.Add(textBox2);
textBox2.SetBinding(TextBox.TextProperty,new Binding("Text") { ElementName= "tbx1" });
this.Content = stackPanel;
}
}
}
8)RelativeSource
Object->MarkupExtension->RelativeSource
实现一个标记扩展,该扩展描述相对于绑定目标位置的绑定源位置。
名称 | 备注 | 权限 |
---|---|---|
以 FindAncestor 模式获取或设置要查找的上级级别。 使用 1 指示最靠近绑定目标元素的项。 | get; set; | |
获取或设置要查找的上级节点的类型。 | get; set; | |
获取或设置 RelativeSourceMode 值,该值描述相对于绑定目标的位置的绑定源的位置。 | get; set; | |
获取一个静态值,该值用于返回为 RelativeSource 模式构造的 PreviousData。 | get; | |
获取一个静态值,该值用于返回为 RelativeSource 模式构造的 Self。 | get; | |
获取一个静态值,该值用于返回为 RelativeSource 模式构造的 TemplatedParent。 | get; |
名称 | 备注 | 权限 |
---|---|---|
返回一个应设置为此标记扩展的目标对象属性上的值的对象。 对于 RelativeSource,这是另一个 RelativeSource,它使用指定模式的适当的源。 | public | |
指示是否应使 AncestorLevel 属性持久化。 | public | |
指示是否应使 AncestorType 属性持久化。 | public |
名称 | 备注 |
---|---|
void ISupportInitialize.BeginInit (); | |
void ISupportInitialize.EndInit (); |
RelativeSourceMode
名称 | 值 | 备注 |
---|---|---|
FindAncestor | 3 | 引用数据绑定元素的父链中的上级。 这可用于绑定到特定类型的上级或其子类。 如果您要指定 AncestorType 和/或 AncestorLevel,可以使用此模式。 |
PreviousData | 0 | 允许在当前显示的数据项列表中绑定上一个数据项(不是包含数据项的控件)。 |
Self | 2 | 引用正在其上设置绑定的元素,并允许你将该元素的一个属性绑定到同一元素的其他属性上。 |
TemplatedParent | 1 | 引用应用了模板的元素,其中此模板中存在数据绑定元素。 这类似于设置 TemplateBindingExtension,并仅当 Binding 在模板中时适用。 |
- FindAncestor(绑定到父元素)
XAML范例
<Window
x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="400"
Height="250"
mc:Ignorable="d">
<StackPanel x:Name="sp1">
<TextBlock x:Name="tbk1" Margin="5" Text="TextBlock1" />
<StackPanel x:Name="sp2">
<TextBlock x:Name="tbk2" Margin="5" Text="TextBlock2" />
<StackPanel x:Name="sp3">
<TextBlock x:Name="tbk3" Margin="5" Text="TextBlock3" />
<Label x:Name="lbl1" Content="Label1"/>
<StackPanel x:Name="sp4">
<TextBox x:Name="tbx1" Margin="5" Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}, AncestorLevel=2}, Path=Name}" />
</StackPanel>
</StackPanel>
<Button Margin="5" Content="MesShow" />
</StackPanel>
</StackPanel>
</Window>
后台代码不变
C#代码
<Window
x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="400"
Height="250"
mc:Ignorable="d">
<StackPanel x:Name="sp1">
<TextBlock x:Name="tbk1" Margin="5" Text="TextBlock1" />
<StackPanel x:Name="sp2">
<TextBlock x:Name="tbk2" Margin="5" Text="TextBlock2" />
<StackPanel x:Name="sp3">
<TextBlock x:Name="tbk3" Margin="5" Text="TextBlock3" />
<Label x:Name="lbl1" Content="Label1"/>
<StackPanel x:Name="sp4">
<TextBox x:Name="tbx1" Margin="5"/>
</StackPanel>
</StackPanel>
<Button Margin="5" Content="MesShow" />
</StackPanel>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Xml;
namespace BindingSourceDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Binding myBinding = new Binding();
myBinding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(StackPanel), 2);
myBinding.Path = new PropertyPath("Name");
tbx1.SetBinding(TextBox.TextProperty, myBinding);
}
}
}
- Self(自身的属性绑定到另一个属性)
XAML范例
<Window
x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="400"
Height="250"
mc:Ignorable="d">
<StackPanel x:Name="sp1">
<TextBlock x:Name="tbk1" Margin="5" Text="{Binding RelativeSource={RelativeSource Self},Path=Name}" />
</StackPanel>
</Window>
后台默认
C#代码
前台默认
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Xml;
namespace BindingSourceDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
StackPanel sp1 = new StackPanel();
TextBlock tbk1 = new TextBlock();
tbk1.Margin = new Thickness(5);
tbk1.Name = "tbk1";
RegisterName("tbk1", tbk1);
Binding myBinding = new Binding();
myBinding.RelativeSource = new RelativeSource(RelativeSourceMode.Self);
myBinding.Path = new PropertyPath("Name");
tbk1.SetBinding(TextBlock.TextProperty, myBinding);
sp1.Children.Add(tbk1);
this.Content = sp1;
}
}
}
- TemplatedParent
XAML范例
<Window
x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="400"
Height="250"
mc:Ignorable="d">
<Window.Resources>
<Style TargetType="Button">
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Ellipse Fill="{TemplateBinding Background}" Stroke="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Foreground}" StrokeThickness="5" />
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Button Margin="5" Background="Aqua" Foreground="Red" />
</Window>
- PreviousData(允许您绑定所显示数据项列表中以前的数据项(不是包含数据项的控件))
XAML范例(引用https://www.cnblogs.com/loveis715/archive/2011/12/15/2288272.html)
<Window
x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BindingSourceDemo"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:collection="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow"
Width="400"
Height="200"
mc:Ignorable="d">
<Window.Resources>
<collection:ArrayList x:Key="cillectionkey">
<sys:String>第一项</sys:String>
<sys:String>第二项</sys:String>
<sys:String>第三项</sys:String>
<sys:String>第四项</sys:String>
</collection:ArrayList>
</Window.Resources>
<StackPanel Orientation="Vertical">
<ListBox ItemsSource="{StaticResource ResourceKey=cillectionkey}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}"></TextBlock>
<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=PreviousData}}" Margin="15 0 0 0"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Window>
后台代码不变。
9)ObjectDataProvider
Object->DataSourceProvider->ObjectDataProvider
- 把ObjectDataProvider对象当做Binding的Source来使用时,这个对象本身就代表了数据(方法的返回数据),所以Path使用".",而非Data.
- MethodParameters不是依赖属性,不能作为绑定目标。(基类含PropertyChanged)
- 数据驱动UI的理想是尽可能地使用数据对象作为Binding的Source而把UI元素当做Binding的Target。
名称 | 备注 | 权限 |
---|---|---|
获取基础数据对象。 | get; | |
获取或设置要 Dispatcher 使用的 UI 线程的当前对象。 | get; set; | |
获取最新查询操作的错误。 | get; | |
获取或设置一个值,该值指示是否阻止或延迟数据自动加载。 | get; set; | |
获取一个值,该值指示是否有某个未完成的 DeferRefresh() 正在运行。 | get; |
名称 | 备注 | 权限 |
---|---|---|
指示即将开始初始化此对象;在调用匹配的 Refresh() 方法前不要进行隐式 EndInit()。 | protected | |
在派生类中重写此基类时,如果已调用 InitialLoad() 或 Refresh(),那么此基类会调用此方法。 如果刷新发生延迟或已禁用初始加载,则基类会延迟调用。 | protected | |
进入延迟循环,该循环可用于更改提供程序的属性并延迟自动刷新。 | public | |
表示此对象的初始化已完成;如果没有其他未完成的 Refresh(),则这会导致 DeferRefresh()。 | protected | |
启动对基础数据模型的初始查询。 结果返回到 Data 属性。 | public | |
通过提供的参数引发 PropertyChanged 事件。 | protected | |
派生类调用此方法以指示查询已完成。 | protected | |
启动对基础数据模型的刷新操作。 结果返回到 Data 属性。 | public |
名称 | 备注 |
---|---|
在 Data 属性具有一个新值时发生。 | |
在属性值更改时发生。 | |
INotifyPropertyChanged.PropertyChanged | 在属性值更改时发生。 |
名称 | 备注 |
---|---|
void ISupportInitialize.BeginInit (); | |
void ISupportInitialize.EndInit (); |
名称 | 备注 | 权限 |
---|---|---|
获取要传递给该构造函数的参数列表。 | get; | |
获取或设置一个值,该值指示是在辅助线程还是在活动上下文中执行对象创建。 | get; set; | |
获取或设置要调用的方法的名称。 | get; set; | |
获取要传递给方法的参数列表。 | get; | |
获取或设置用作绑定源的对象。 | get; set; | |
获取或设置要创建其实例的对象的类型。 | get; set; |
名称 | 备注 | 权限 |
---|---|---|
根据 IsAsynchronous 属性的值,立即开始创建请求的对象,或在后台线程上开始创建。 | protected | |
指示是否应使 ConstructorParameters 属性持久化。 | public | |
指示是否应使 MethodParameters 属性持久化。 | public | |
指示是否应使 ObjectInstance 属性持久化。 | public | |
指示是否应使 ObjectType 属性持久化。 | public |
范例:
<Window x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingSourceDemo"
mc:Ignorable="d"
Title="MainWindow" Height="250" Width="400">
<StackPanel>
<TextBox x:Name="tbx1" Margin="5"/>
<TextBox x:Name="tbx2" Margin="5"/>
<TextBox x:Name="tbx3" Margin="5"/>
<Button Content="MesShow" Click="OnClick"/>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Xml;
namespace BindingSourceDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ObjectDataProvider objectDataProvider = new ObjectDataProvider();
objectDataProvider.ObjectInstance = new MessageShow();
objectDataProvider.MethodName = "MesAdd";
objectDataProvider.MethodParameters.Add("TextBox 1");
objectDataProvider.MethodParameters.Add("TextBox 2");
Binding binding0 = new Binding("MethodParameters[0]")
{
Source = objectDataProvider,
BindsDirectlyToSource = true,
UpdateSourceTrigger= UpdateSourceTrigger.PropertyChanged
};
Binding binding1 = new Binding("MethodParameters[1]")
{
Source = objectDataProvider,
BindsDirectlyToSource = true,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
Binding binding2 = new Binding(".") { Source = objectDataProvider };
tbx1.SetBinding(TextBox.TextProperty, binding0);
tbx2.SetBinding(TextBox.TextProperty, binding1);
tbx3.SetBinding(TextBox.TextProperty, binding2);
}
class MessageShow
{
public string MesAdd(string s1, string s2)
{
return s1 + s2;
}
public void MesShow(string s1, string s2)
{
MessageBox.Show(MesAdd( s1, s2));
}
}
private void OnClick(object sender, RoutedEventArgs e)
{
ObjectDataProvider objectDataProvider = new ObjectDataProvider();
objectDataProvider.ObjectInstance = new MessageShow();
objectDataProvider.MethodName = "MesShow";
objectDataProvider.MethodParameters.Add("object");
objectDataProvider.MethodParameters.Add("DataProvider");
if (objectDataProvider.Data != null) return;
}
}
}
10)LINQ
范例:
<Window x:Class="BindingSourceDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingSourceDemo"
mc:Ignorable="d"
Title="MainWindow" Height="250" Width="400">
<StackPanel>
<ListView x:Name="lvw1" >
<ListView.View>
<GridView>
<GridViewColumn Header="Id" Width="60" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Name" Width="100" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Age" Width="80" DisplayMemberBinding="{Binding Age}"/>
</GridView>
</ListView.View>
</ListView>
<Button Content="Select T" Click="OnClick"/>
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Xml;
namespace BindingSourceDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
List<Student> students = new List<Student>()
{
new Student(){Id=0,Name="Tim",Age=29},
new Student(){Id=1,Name="Tom",Age=28},
new Student(){Id=2,Name="Kyle",Age=27},
new Student(){Id=3,Name="Tony",Age=26},
new Student(){Id=4,Name="Vina",Age=25},
new Student(){Id=5,Name="Mike",Age=24}
};
public MainWindow()
{
InitializeComponent();
lvw1.ItemsSource = students;
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
private void OnClick(object sender, RoutedEventArgs e)
{
lvw1.ItemsSource = from stu in students where stu.Name.StartsWith("T") select stu;
}
}
}
DataTable
DataTable dt = this.GetDataTable();
lvw1.ItemsSource = from row in dt.Rows.Cast<DataGridRow>()
where Convert.ToString(row["Name"]).StartsWith("T")
select new Student
{
Id = int.Parse(row["Id"].ToString()),
Name = row["Name"].ToString(),
Age = int.Parse(row["Age"].ToString())
};
XML
<?xml version="1.0" encoding="utf-8" ?>
<StudentList>
<Class>
<Student Id="0" Name="Tim" Age="29"/>
<Student Id="1" Name="Tom" Age="28"/>
<Student Id="2" Name="Mess" Age="27"/>
</Class>
<Class>
<Student Id="3" Name="Tony" Age="26"/>
<Student Id="4" Name="Vina" Age="25"/>
<Student Id="5" Name="Emily" Age="24"/>
</Class>
</StudentList>
System.Xml.Linq.XDocument xmlDocument = System.Xml.Linq.XDocument.Load(@"G:\c#\WPF深入浅出\BindingSourceDemo\myXML.xml");
lvw1.ItemsSource = from element in xmlDocument.Descendants("Student")
where element.Attribute("Name").Value.StartsWith("T")
select new Student()
{
Id = int.Parse(element.Attribute("Id").Value),
Name = element.Attribute("Name").Value,
Age = int.Parse(element.Attribute("Age").ToString())
};
Binding路径
Binding.Path,获取或设置绑定源属性的路径。属性值:PropertyPath.
1)没有Path的绑定(绑定源本身是数据且不需要Path来指明)
<Window x:Class="BindingDemo2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingDemo2"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<Window.Resources>
<sys:String x:Key="string1" >
sring
</sys:String>
</Window.Resources>
<StackPanel>
<TextBlock x:Name="tbk1" Text="{Binding Source={StaticResource string1}}"/>
</StackPanel>
</Window>
2)Path是"."(绑定源本身是数据且不需要Path来指明)
<Window x:Class="BindingDemo2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingDemo2"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<Window.Resources>
<sys:String x:Key="string1" >
sring
</sys:String>
</Window.Resources>
<StackPanel>
<TextBlock x:Name="tbk1" Text="{Binding Source={StaticResource string1}, Path=.}"/>
</StackPanel>
</Window>
或
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string str =String.Empty;
str = "string";
TextBox tbx1 = new TextBox();
StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(tbx1);
this.Content = stackPanel;
tbx1.SetBinding(TextBox.TextProperty, new Binding(".") { Source = str });
}
}
3)Path为绑定对象的某个属性(依赖属性)
<Window x:Class="BindingDemo2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingDemo2"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<Window.Resources>
<sys:String x:Key="string1" >
sring
</sys:String>
</Window.Resources>
<StackPanel>
<TextBlock x:Name="tbk1" Text="{Binding Source={StaticResource string1}, Path=Length}"/>
</StackPanel>
</Window>
或
public MainWindow()
{
InitializeComponent();
string str =String.Empty;
str = "string";
TextBox tbx1 = new TextBox();
StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(tbx1);
this.Content = stackPanel;
tbx1.SetBinding(TextBox.TextProperty, new Binding("Length") { Source = str });
}
4)Path为索引器([n]或.[n])
<Window x:Class="BindingDemo2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingDemo2"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<Window.Resources>
<x:Array Type="sys:Int16" x:Key="array" >
<sys:Int16 >10</sys:Int16>
<sys:Int16 >11</sys:Int16>
<sys:Int16 >12</sys:Int16>
<sys:Int16 >13</sys:Int16>
</x:Array>
</Window.Resources>
<StackPanel>
<TextBlock x:Name="tbk1" Text="{Binding Source={StaticResource array}, Path=[1]}"/>
</StackPanel>
</Window>
或
public MainWindow()
{
InitializeComponent();
int[] array = new int[4] { 10, 11, 12, 13 };
TextBox tbx1 = new TextBox();
StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(tbx1);
this.Content = stackPanel;
tbx1.SetBinding(TextBox.TextProperty, new Binding() { Source = array, Path=new PropertyPath("[1]") });
}
<Window x:Class="BindingDemo2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingDemo2"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<StackPanel>
<TextBox x:Name="tbx1" Text="0123456789"/>
<TextBlock x:Name="tbk1" Text="{Binding ElementName=tbx1, Path=Text.[3] }"/>
</StackPanel>
</Window>
或
<Window x:Class="BindingDemo2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindingDemo2"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<StackPanel>
<TextBox x:Name="tbx1" Text="0123456789"/>
<TextBlock x:Name="tbk1" Text="{Binding ElementName=tbx1, Path=Text[3] }"/>
</StackPanel>
</Window>
或
public MainWindow()
{
InitializeComponent();
TextBox tbx1 = new TextBox { Text="0123456789"};
TextBlock tbk1 = new TextBlock ();
StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(tbx1);
stackPanel.Children.Add(tbk1);
this.Content = stackPanel;
tbk1.SetBinding(TextBlock.TextProperty, new Binding() { Source = tbx1, Path=new PropertyPath("Text.[3]") });
}
5)Path中含"\"
public MainWindow()
{
InitializeComponent();
List<string> list = new List<string>() { "Fiset", "Second", "Third" };
TextBlock tbk1 = new TextBlock();
TextBlock tbk2 = new TextBlock();
TextBlock tbk3 = new TextBlock();
StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(tbk1);
stackPanel.Children.Add(tbk2);
stackPanel.Children.Add(tbk3);
this.Content = stackPanel;
tbk1.SetBinding(TextBlock.TextProperty, new Binding() { Source = list, Path = new PropertyPath("/") });
tbk2.SetBinding(TextBlock.TextProperty, new Binding() { Source = list, Path = new PropertyPath("/Length") });
tbk3.SetBinding(TextBlock.TextProperty, new Binding() { Source = list, Path = new PropertyPath("/[1]") });
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Student student = new Student { Name = "myStudent" };
Class class1 = new Class { Name = "myClass",ItsStudent= student };
School school = new School {Name="mySchool", ItsClass= class1 };
List<School> list = new List<School>();
list.Add(school);
//List<string> list = new List<string>() { "Fiset", "Second", "Third" };
TextBlock tbk1 = new TextBlock();
TextBlock tbk2 = new TextBlock();
TextBlock tbk3 = new TextBlock();
StackPanel stackPanel = new StackPanel();
stackPanel.Children.Add(tbk1);
stackPanel.Children.Add(tbk2);
stackPanel.Children.Add(tbk3);
this.Content = stackPanel;
tbk1.SetBinding(TextBlock.TextProperty, new Binding() { Source = list, Path = new PropertyPath("/Name") });
tbk2.SetBinding(TextBlock.TextProperty, new Binding() { Source = list, Path = new PropertyPath("/ItsClass.Name") });
tbk3.SetBinding(TextBlock.TextProperty, new Binding() { Source = list, Path = new PropertyPath("/ItsClass.ItsStudent.Name") });
}
public class School
{
public string Name { get; set; }
public Class ItsClass { get; set; }
}
public class Class
{
public string Name { get; set; }
public Student ItsStudent { get; set; }
}
public class Student
{
public string Name { get; set; }
}
}
}
Binding方向
Binding.Mode:属性值,BindingMode。
- Default:Binding的模式根据目标的实际情况而定。
- OneTime:该绑定会使源属性初始化目标属性,但不传播后续更改。
- OneWay:在更改绑定源(源)时更新绑定目标(目标)。
- OneWayToSource:在目标属性更改时,更新源属性。
- TwoWay:导致更改源属性或目标属性时自动更新另一方。
<Window
x:Class="BindingDirectionDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BindingDirectionDemo"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="450"
Height="200"
mc:Ignorable="d">
<StackPanel>
<TextBox Text="{Binding Path=Value, ElementName=sld1, Mode="改变Mode值"}"/>
<Slider x:Name="sld1" Value="5" AutoToolTipPlacement="BottomRight" AutoToolTipPrecision="6"/>
</StackPanel>
</Window>
Default:默认值
OneTime
OneWay
OneWayToSource
TwoWay
Binding.UpdateSourceTrigger
获取或设置一个值,它可确定绑定源更新的计时。
UpdateSourceTrigger
- Default:绑定目标属性的默认 UpdateSourceTrigger 值。 大多数依赖属性的默认值为 PropertyChanged,而 Text 属性的默认值为 LostFocus。
- Explicit:仅在调用 UpdateSource() 方法时更新绑定源。
- LostFocus:每当绑定目标元素失去焦点时,都会更新绑定源。
- PropertyChanged:每当绑定目标属性发生更改时,都会更新绑定源。
<Window
x:Class="BindingDirectionDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BindingDirectionDemo"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="450"
Height="200"
mc:Ignorable="d">
<StackPanel>
<TextBox Text="{Binding Path=Value, ElementName=sld1, Mode=TwoWay}"/>
<Slider x:Name="sld1" Value="5" AutoToolTipPlacement="BottomRight" AutoToolTipPrecision="6"/>
</StackPanel>
</Window>
Default:(LostFocus)
输入数值后,当TextBox失去焦点时,更新绑定源。
Explicit
<Window
x:Class="BindingDirectionDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BindingDirectionDemo"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="450"
Height="200"
mc:Ignorable="d">
<StackPanel>
<TextBox Text="{Binding Path=Value, ElementName=sld1, Mode=TwoWay, UpdateSourceTrigger=Explicit }" />
<Slider x:Name="sld1" AutoToolTipPlacement="BottomRight" AutoToolTipPrecision="6" Value="5" />
<Button Click="OnClik" Content=" UpdateSource" />
</StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace BindingDirectionDemo
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OnClik(object sender, RoutedEventArgs e)
{
foreach (var item in ((sender as Button).Parent as StackPanel).Children)
{
if(item is TextBox)
{
BindingExpression bindingExpression = BindingOperations.GetBindingExpression((item as TextBox),TextBox.TextProperty);
bindingExpression.UpdateSource();
}
}
}
}
}
PropertyChanged