一般情况下,应用程序会有三层结构:数据存储层,数据处理层(业务逻辑层),数据展示层(UI界面)。

WPF是“数据驱动UI”。

  • Binding实现(通过纯C#代码)

  Binding分为source和target,即源和目标。

  如何通过Binging实现UI元素和代码对象的连接。

  首先绑定源对象要实现INotifyPropertyChanged接口,该接口引用自System.ComponentModel命名空间,所有使用前要引用该命名空间。该接口有一个PropertyChanged事件,可以帮助自动监听源对象的属性变化。

 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.ComponentModel;
class Student:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string name; public string Name
{
get { return name; }
set {
name = value;
if(this.PropertyChanged!=null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
} }

如上代码所示,在绑定了接口以后,当Name属性的值发生变化时,就会自动通知,然后刷新UI元素进行更新。

当然还没有结束,我们现在需要添加界面。然后在后台代码中设置Binding

其实在textBox元素中已经为我们封装好了这些,即SetBinding方法。

所以可以改写如下:

  • 标记扩展进行Data Binding
  • 控制Binding数据流向的是Mode属性,而控制数据更新的是UpdateSourceTrigger属性
  • 没有Path的Binding

  有时候,Binding源本身就是数据,比如字符串,或者int类型,他们的实例本身就是数据,而不需要通过属性来提供访问,那么在指定path时可以通过一个.来代替,或者直接不写path,在XAML代码里可以省略不写,在C#代码中必须显式写.来表示path指向实例本身。

  • 为Binding指定源的几种方法

  • Binding过程中可以没有path,那么可不可以没有source,当然可以,可以通过添加DataContext来隐式表达source。
  • 使用集合对象作为列表控件的ItemsSource
 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.ComponentModel; namespace WpfApp7
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent(); //准备数据源
List<Student> stuList = new List<Student>()
{
new Student(){Id=,Name="Tim",Age=},
new Student(){Id=,Name="Tom",Age=},
new Student(){Id=,Name="Kyle",Age=},
new Student(){Id=,Name="Tony",Age=},
new Student(){Id=,Name="Vina",Age=},
};
//为listBox设置Binding
this.listBoxStudents.ItemsSource = stuList;
this.listBoxStudents.DisplayMemberPath = "Name";
//为TextBox设置Binding
Binding binding = new Binding("SelectedItem.Id") { Source = this.listBoxStudents };
this.textBoxId.SetBinding(TextBox.TextProperty, binding);
}
} class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; } } }

界面代码如下:

<Window x:Class="WpfApp7.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:WpfApp7"
mc:Ignorable="d"
Title="Binding Source" Height="240" Width="300">
<StackPanel x:Name="stackPanel1" Background="LightBlue">
<TextBlock Text="Student ID" FontWeight="Bold" Margin="5"/>
<TextBox x:Name="textBoxId" Margin="5"/>
<TextBlock Text="Student List" FontWeight="Bold" Margin="5"/>
<ListBox x:Name="listBoxStudents" Height="110" Margin="5"/> </StackPanel>
</Window>
  • 使用ObjectDataProvider对象作为Binding的Source

现在有一个Calculator的类,他具有加减乘除的方法:

 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 ObjectDateProvider
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.SetBinding();
} private void SetBinding()
{
//创建并配置ObjectDataProvider对象
ObjectDataProvider odp = new ObjectDataProvider
{
ObjectInstance = new Calculator(),
MethodName = "Add"
};
odp.MethodParameters.Add("");
odp.MethodParameters.Add("");
//以ObjectDataProvider对象为Source创建Binding
Binding bindingToArg1 = new Binding("MethodParameters[0]")
{
Source = odp,
BindsDirectlyToSource = true,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
Binding bindingToArg2 = new Binding("MethodParameters[1]")
{
Source = odp,
BindsDirectlyToSource = true,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
}; Binding bindingToResult = new Binding(".") { Source = odp }; //将Binding关联到UI元素上
this.textBoxArg1.SetBinding(TextBox.TextProperty, bindingToArg1);
this.textBoxArg2.SetBinding(TextBox.TextProperty, bindingToArg2);
this.textBoxResult.SetBinding(TextBox.TextProperty, bindingToResult);
}
} class Calculator
{
public string Add(string arg1,string arg2)
{
double x = ;
double y = ;
double z = ;
if(double.TryParse(arg1,out x)&&double.TryParse(arg2,out y))
{
z = x + y;
return z.ToString();
}
return "Input Error";
}
}
}

界面代码如下:

 <Window x:Class="ObjectDateProvider.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:ObjectDateProvider"
mc:Ignorable="d"
Title="MainWindow" Height="135" Width="300">
<StackPanel Background="LightBlue">
<TextBox x:Name="textBoxArg1" Margin="5"/>
<TextBox x:Name="textBoxArg2" Margin="5"/>
<TextBox x:Name="textBoxResult" Margin="5"/> </StackPanel>
</Window>

界面代码

  • 使用Binding的RelativeSource
  1. Binding对数据的转换与校验

  Binding用于数据有效性检验的是ValidationRules属性,用于数据类型转换关卡的是Converter属性。

  

WPF之数据绑定Data Binding的更多相关文章

  1. [WPF]如何调试Data Binding

    前言 在WPF开发中,将ViewModel中对象绑定到UI上时,会出现明明已经将数据对象Binding到UI,但是UI上就是不显示等等的问题.这篇博客将介绍WPF Data Binding相关的内容, ...

  2. WPF QuickStart系列之数据绑定(Data Binding)

    这篇博客将展示WPF DataBinding的内容. 首先看一下WPF Data Binding的概览, Binding Source可以是任意的CLR对象,或者XML文件等,Binding Targ ...

  3. WPF中的数据绑定Data Binding使用小结

    完整的数据绑定的语法说明可以在这里查看: http://www.nbdtech.com/Free/WpfBinding.pdf MSDN资料: Data Binding: Part 1 http:// ...

  4. WPF中的Data Binding调试指南

    大家平时做WPF开发,相信用Visual studio的小伙伴比较多.XAML里面曾经在某些特殊版本的Visual Studio中是可以加断点进行调试的,不过目前多数版本都不支持在XAML加断点来调试 ...

  5. Windows phone 8.1之数据绑定(Data Binding)

    学习Winphone8.1的时候经常需要对Slider进行数据绑定后使之视觉化,方便调节Slider的值. 数据绑定分为源(Source)和目标(Target),Source一般分为两种,其他控件的数 ...

  6. WP8.1 Study5:Data binding数据绑定

    一.数据绑定 最简单的编程UI控件的方法是写自己的数据来获取和设置控件的属性,e.g. , textBox1.Text = "Hello, world"; 但在复杂的应用程序,这样 ...

  7. [WPF系列]-DataBinding(数据绑定) 自定义Binding

    自定义Binding A base class for custom WPF binding markup extensions BindingDecoratorBase Code: public c ...

  8. XAML数据绑定(Data Binding)

    XAML数据绑定(Data Binding)   Data Binding可以使得XAML标签属性的赋值更为灵活和方便.在绑定过程中,获取数据的标签成为目标标签:提供数据的标签成为源标签.在XAML中 ...

  9. .NET: WPF Data Binding

    WPF是分离UI和Logic的最佳工具,不同于Window Form的事件驱动原理,WPF采用的是数据驱动,让UI成为了Logic的附属,达到分离的效果. 本篇主要讲讲wpf的精华:data bind ...

随机推荐

  1. Netflix:当你按下“播放”的时候发生了什么?

    从用户端来看,使用Netflix是很简单的,按下播放键之后视频就像变魔术一样完美呈现了.看起来很容易是吧?然而实际不是这样的.了解过云计算的人可能会简单地以为,既然Netflix使用AWS来提供视频服 ...

  2. CentOS7.x上轻量级TCP转发工具rinetd的安装配置

    一.实验背景 Linux下端口转发一般都使用iptables来实现,使用iptables可以很容易将TCP和UDP端口从防火墙转发到内部主机上. 如果需要将流量从专用地址转发到不在您当前网络上的机器上 ...

  3. 网络流--最大流--hlpp(预流推进)模板

    //500ms 秒掉洛谷推流问题 #include <algorithm> #include <iostream> #include <cstring> #incl ...

  4. P5960 差分约束算法模板

    差分约束 差分约束,一般用来解决有\(n\)个未知数,\(m\)个不等式方程的问题,形如: \[\begin{cases} \ x_{a_1}-x_{b_1}\leq y_1\\ \ x_{a_2}- ...

  5. SaltStack漏洞导致的挖矿排查思路

    描述 SaltStack是一套C/S架构的运维工具,服务端口默认为4505/4506,两个端口如果对外网开放危害非常大,黑客利用SaltStack的远程命令执行漏洞CVE-2020-11651可以直接 ...

  6. 首次使用AWS服务器EC2

    AWS有一年的免费套餐,这个便宜我得占. 申请的时候需要填写银行卡,AWS暂不支持储蓄卡,只好绑信用卡了. 创建EC2实例之后,下一个要解决的问题就是远程root访问. 1. 修改安全组设置 2. s ...

  7. JS对象与原型

    一. JS的对象 1.1 创建对象的几种方式 1.1.1 通过字面量创建对象 在js中,一对{} 其实就是一个对象 var person = { name: "tom", age: ...

  8. System.Linq.Dynamic字符串转委托

    以前一直想着有没有一个方法能够把字符串直接转化成函数的,刚好有需求就找了下,还真有. 微软地址:https://docs.microsoft.com/en-us/previous-versions/b ...

  9. CODING 敏捷实战系列课第二讲:Scrum 敏捷项目管理核心要素之 3355

    Scrum 是敏捷开发流派中最著名和最落地的一支,全球 70% 以上公司的敏捷转型都是以 Scrum 起步.CODING 特邀敏捷顾问.CST & CTC 认证敏捷教练申健老师将在本课程< ...

  10. python执行脚本报错: Non-ASCII character '\xe4' in file yang.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

    这是因为我们在写python程序的时候,无论在注释里面出现中文,还是在代码里面出现中文,也就是说只要这个python程序里面有中文,我们就不能直接用python2来进行执行,如果安装是python3可 ...