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

WPF是“数据驱动UI”。

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

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

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

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Navigation;
  14. using System.Windows.Shapes;
  15. using System.ComponentModel;
  16. class Student:INotifyPropertyChanged
  17. {
  18. public event PropertyChangedEventHandler PropertyChanged;
  19. private string name;
  20.  
  21. public string Name
  22. {
  23. get { return name; }
  24. set {
  25. name = value;
  26. if(this.PropertyChanged!=null)
  27. {
  28. this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
  29. }
  30. }
  31. }
  32.  
  33. }

如上代码所示,在绑定了接口以后,当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
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Navigation;
  14. using System.Windows.Shapes;
  15. using System.ComponentModel;
  16.  
  17. namespace WpfApp7
  18. {
  19. /// <summary>
  20. /// MainWindow.xaml 的交互逻辑
  21. /// </summary>
  22. public partial class MainWindow : Window
  23. {
  24. public MainWindow()
  25. {
  26. InitializeComponent();
  27.  
  28. //准备数据源
  29. List<Student> stuList = new List<Student>()
  30. {
  31. new Student(){Id=,Name="Tim",Age=},
  32. new Student(){Id=,Name="Tom",Age=},
  33. new Student(){Id=,Name="Kyle",Age=},
  34. new Student(){Id=,Name="Tony",Age=},
  35. new Student(){Id=,Name="Vina",Age=},
  36. };
  37. //为listBox设置Binding
  38. this.listBoxStudents.ItemsSource = stuList;
  39. this.listBoxStudents.DisplayMemberPath = "Name";
  40. //为TextBox设置Binding
  41. Binding binding = new Binding("SelectedItem.Id") { Source = this.listBoxStudents };
  42. this.textBoxId.SetBinding(TextBox.TextProperty, binding);
  43. }
  44. }
  45.  
  46. class Student
  47. {
  48. public int Id { get; set; }
  49. public string Name { get; set; }
  50. public int Age { get; set; }
  51.  
  52. }
  53.  
  54. }

界面代码如下:

  1. <Window x:Class="WpfApp7.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:local="clr-namespace:WpfApp7"
  7. mc:Ignorable="d"
  8. Title="Binding Source" Height="240" Width="300">
  9. <StackPanel x:Name="stackPanel1" Background="LightBlue">
  10. <TextBlock Text="Student ID" FontWeight="Bold" Margin="5"/>
  11. <TextBox x:Name="textBoxId" Margin="5"/>
  12. <TextBlock Text="Student List" FontWeight="Bold" Margin="5"/>
  13. <ListBox x:Name="listBoxStudents" Height="110" Margin="5"/>
  14.  
  15. </StackPanel>
  16. </Window>
  • 使用ObjectDataProvider对象作为Binding的Source

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Navigation;
  14. using System.Windows.Shapes;
  15.  
  16. namespace ObjectDateProvider
  17. {
  18. /// <summary>
  19. /// MainWindow.xaml 的交互逻辑
  20. /// </summary>
  21. public partial class MainWindow : Window
  22. {
  23. public MainWindow()
  24. {
  25. InitializeComponent();
  26. this.SetBinding();
  27. }
  28.  
  29. private void SetBinding()
  30. {
  31. //创建并配置ObjectDataProvider对象
  32. ObjectDataProvider odp = new ObjectDataProvider
  33. {
  34. ObjectInstance = new Calculator(),
  35. MethodName = "Add"
  36. };
  37. odp.MethodParameters.Add("");
  38. odp.MethodParameters.Add("");
  39. //以ObjectDataProvider对象为Source创建Binding
  40. Binding bindingToArg1 = new Binding("MethodParameters[0]")
  41. {
  42. Source = odp,
  43. BindsDirectlyToSource = true,
  44. UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
  45. };
  46. Binding bindingToArg2 = new Binding("MethodParameters[1]")
  47. {
  48. Source = odp,
  49. BindsDirectlyToSource = true,
  50. UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
  51. };
  52.  
  53. Binding bindingToResult = new Binding(".") { Source = odp };
  54.  
  55. //将Binding关联到UI元素上
  56. this.textBoxArg1.SetBinding(TextBox.TextProperty, bindingToArg1);
  57. this.textBoxArg2.SetBinding(TextBox.TextProperty, bindingToArg2);
  58. this.textBoxResult.SetBinding(TextBox.TextProperty, bindingToResult);
  59. }
  60. }
  61.  
  62. class Calculator
  63. {
  64. public string Add(string arg1,string arg2)
  65. {
  66. double x = ;
  67. double y = ;
  68. double z = ;
  69. if(double.TryParse(arg1,out x)&&double.TryParse(arg2,out y))
  70. {
  71. z = x + y;
  72. return z.ToString();
  73. }
  74. return "Input Error";
  75. }
  76. }
  77. }

界面代码如下:

  1. <Window x:Class="ObjectDateProvider.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:local="clr-namespace:ObjectDateProvider"
  7. mc:Ignorable="d"
  8. Title="MainWindow" Height="135" Width="300">
  9. <StackPanel Background="LightBlue">
  10. <TextBox x:Name="textBoxArg1" Margin="5"/>
  11. <TextBox x:Name="textBoxArg2" Margin="5"/>
  12. <TextBox x:Name="textBoxResult" Margin="5"/>
  13.  
  14. </StackPanel>
  15. </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. bfs—Catch That Cow—poj3278

    Catch That Cow Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 87152   Accepted: 27344 ...

  2. C#模板编程(2): 编写C#预处理器,让模板来的再自然一点

    在<C#模板编程(1):有了泛型,为什么还需要模板?>文中,指出了C#泛型的局限性,为了突破这个局限性,我们需要模板编程.但是,C#语法以及IDE均不支持C#模板编程,怎么办呢?自己动手, ...

  3. 基于opencv的人脸识别程序

    1. 解析opencv自带人脸识别源码(……/opencv-3.1.0/samples/cpp/facedetect.cpp) @ 操作系统:Ubuntu 15.04 OpenCV版本:3.1.0 # ...

  4. 贪心--HDU 2021 发工资咯

    Description 作为杭电的老师,最盼望的日子就是每月的8号了,因为这一天是发工资的日子,养家糊口就靠它了,呵呵,但是对于学校财务处的工作人员来说,这一天则是很忙碌的一天,财务处的小胡老师最近就 ...

  5. VS Code 全部快捷键一览表(巨TM全)

    常用 General 按 Press 功能 Function Ctrl + Shift + P,F1 显示命令面板 Show Command Palette Ctrl + P 快速打开 Quick O ...

  6. 图论--双连通E-DCC缩点模板

    // tarjan算法求无向图的桥.边双连通分量并缩点 #include<iostream> #include<cstdio> #include<cstring> ...

  7. 图论--LCA--在线RMQ ST

    板子测试POJ1330,一发入魂,作者是KuangBin神犇,感谢?‍ #include <cstdio> #include <cstring> #include <al ...

  8. 利用github的webhook进行自动部署

    利用github的webhook进行自动部署 github提供了webhook功能,大概意思就是,当你提交了代码,git检测到你进行了push,可以调起你一个你知道的url. 这个功能有什么用了?比如 ...

  9. B. Long Path dp

    https://codeforces.com/problemset/problem/407/B 这个题目是一个dp,有那么一点点的递归的意思,这个应该算一个找规律的dp, dp[i]定义为第一次到第i ...

  10. HDU-6351 Beautiful Now 全排列暴力

    Beautiful Now 题意 给出一个最大为10^9的数字n,以及一个k,你最多交换n中任意两个位置的数字k次,问形成的最大数字和最小数字. 思路 看到这题,我靠这题暴力交换一下,不难啊,咋没人做 ...