一般情况下,应用程序会有三层结构:数据存储层,数据处理层(业务逻辑层),数据展示层(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. Soldiers Sortie

    这部2006年上映的作品豆瓣评分9.3,时至今日仍然有人乐此不疲地讨论剧情和启发,我想称之为经典应该不算过分. 这部剧我至少完整看过3遍,随着阅历增加,对某些角色的体会也变得更深刻. 许三多 许三多是 ...

  2. Android APK 重签名

    对APK 进行在线 加固后,Apk体积一般会变大,而且Apk会无法直接安装,因为缺少了你的签名.是的,你需要对这个Apk进行重签名. 如何重签名 重签名的方法,一般来说,有两种,第一种是用JDK自带的 ...

  3. 2-JVM内存模型

    内存模型 方法区 JDK1.7 之前包含1.7 将方法区称为 Perm Space 永久代 JDK1.8之后包含1.8 将方法区称为 MetaSpace 元空间. 堆(分配内存会大一些) 分配对象.n ...

  4. 简单搜索 kuangbin C D

    C - Catch That Cow POJ - 3278 我心态崩了,现在来回顾很早之前写的简单搜索,好难啊,我怎么写不出来. 我开始把这个写成了dfs,还写搓了... 慢慢来吧. 这个题目很明显是 ...

  5. MySQL连接不上

    access denied for user root @localhost 解决办法: create user 'root'@'localhost' identified by '你的密码'; gr ...

  6. Linux下ffmpeg交叉编译

    1 获取源代码 git clone -b "branch" https://git.ffmpeg.org/ffmpeg.git "branch" 可以是以下的m ...

  7. 关于Fragment的点击切换数据滞留问题

    场景再现:当我使用tabLayout + Fragment 切换不同的fragment时,出现了数据重复显示的问题: 思考逻辑: - 每次切换fragment都会重新获取数据,但是list集合是全局的 ...

  8. 51单片机实战UcosII操作系统

    中断定义为CPU对系统内外发生的异步事件的响应.异步事件是指没有一定时序关系的.随机发生的事件. 与前后台系统中的中断服务子程序不同,uC/OS-Ⅱ要知道当前内核是否正在处理中断.是否脱离中断. OS ...

  9. NOI Online #2 赛后题解

    color 题意 \(\;\) 给定\(p_1,p_2\),要求\(p_1\)的倍数格子填红色,\(p_2\)的倍数格子填蓝色,既是\(p_1\)又是\(p_2\)倍数的格子颜色任选.求是否存在一种填 ...

  10. 手机网页,div内滚动条,以及div内部滚动条拉到底部之后触发事件

    var gao = document.documentElement.clientHeight; var headHeight = parseInt($('.yhead').css('height') ...