ToB企服应用市场:ToB评测及商务社交产业平台

标题: 深入理解 WPF 数据绑定机制 [打印本页]

作者: 拉不拉稀肚拉稀    时间: 2024-10-31 20:04
标题: 深入理解 WPF 数据绑定机制
一、引言

在当代软件开发中,创建具有精良用户体验的图形用户界面(GUI)至关紧张。WPF 作为一种先进的 GUI 技术,提供了强大的数据绑定机制,使得开发人员能够轻松地将数据与用户界面元素举行关联,实现数据的自动更新和显示。理解 WPF 数据绑定机制对于高效开发高质量的 WPF 应用步伐具有紧张意义。
二、WPF 数据绑定概述

(一)什么是 WPF 数据绑定

WPF 数据绑定是一种将数据源与用户界面元素举行关联的技术。通过数据绑定,当数据源中的数据发生变革时,与之绑定的用户界面元素会自动更新显示;反之,当用户在用户界面上举行操作时,数据源中的数据也会相应地举行更新。这种双向的数据交互方式极大地提高了开发服从,淘汰了手动更新数据的繁琐代码。
(二)数据绑定的优势

三、WPF 数据绑定的工作原理

(一)绑定源和绑定目标

在 WPF 数据绑定中,存在绑定源和绑定目标两个概念。绑定源是提供数据的对象,可以是任何实现了特定接口(如 INotifyPropertyChanged)的对象。绑定目标是用户界面元素,如文本框、列表框等,用于显示绑定源中的数据。
(二)绑定路径

绑定路径是用于指定从绑定源到要绑定的数据的路径。例如,如果绑定源是一个包罗多个属性的对象,绑定路径可以指定具体要绑定的属性名称。通过设置精确的绑定路径,WPF 可以准确地找到要绑定的数据。
(三)绑定引擎

WPF 中的绑定引擎负责监控绑定源和绑定目标的变革,并在需要时举行数据的同步。当绑定源中的数据发生变革时,绑定引擎会自动更新绑定目标;当绑定目标中的数据被用户修改时,绑定引擎会将修改后的数据更新到绑定源中。
四、绑定模式

(一)单向绑定

  1. <Window x:Class="WpfApp.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="WPF Data Binding Example">
  5.     <StackPanel>
  6.         <TextBlock Text="{Binding Path=Message, Mode=OneWay}"/>
  7.     </StackPanel>
  8. </Window>
复制代码
  1. using System;
  2. using System.Windows;
  3. namespace WpfApp
  4. {
  5.     public partial class MainWindow : Window
  6.     {
  7.         public MainWindow()
  8.         {
  9.             InitializeComponent();
  10.             DataContext = new ViewModel();
  11.         }
  12.     }
  13.     public class ViewModel
  14.     {
  15.         public string Message { get; set; } = "Hello, WPF Data Binding!";
  16.     }
  17. }
复制代码
(二)双向绑定

  1. <Window x:Class="WpfApp.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="WPF Data Binding Example">
  5.     <StackPanel>
  6.         <TextBox Text="{Binding Path=UserName, Mode=TwoWay}"/>
  7.     </StackPanel>
  8. </Window>
复制代码
  1. using System;
  2. using System.Windows;
  3. namespace WpfApp
  4. {
  5.     public partial class MainWindow : Window
  6.     {
  7.         public MainWindow()
  8.         {
  9.             InitializeComponent();
  10.             DataContext = new ViewModel();
  11.         }
  12.     }
  13.     public class ViewModel
  14.     {
  15.         private string _userName;
  16.         public string UserName
  17.         {
  18.             get { return _userName; }
  19.             set
  20.             {
  21.                 _userName = value;
  22.                 OnPropertyChanged(nameof(UserName));
  23.             }
  24.         }
  25.         public event PropertyChangedEventHandler PropertyChanged;
  26.         protected virtual void OnPropertyChanged(string propertyName)
  27.         {
  28.             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  29.         }
  30.     }
  31. }
复制代码
(三)OneTime 绑定

  1. <Window x:Class="WpfApp.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="WPF Data Binding Example">
  5.     <StackPanel>
  6.         <TextBlock Text="{Binding Path=AppVersion, Mode=OneTime}"/>
  7.     </StackPanel>
  8. </Window>
复制代码
  1. using System;
  2. using System.Windows;
  3. namespace WpfApp
  4. {
  5.     public partial class MainWindow : Window
  6.     {
  7.         public MainWindow()
  8.         {
  9.             InitializeComponent();
  10.             DataContext = new ViewModel();
  11.         }
  12.     }
  13.     public class ViewModel
  14.     {
  15.         public string AppVersion { get; set; } = "1.0.0";
  16.     }
  17. }
复制代码
五、数据验证

(一)验证规则的界说

(二)在数据绑定中应用验证规则

  1. <Window x:Class="WpfApp.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="WPF Data Binding Example">
  5.     <StackPanel>
  6.         <TextBox Text="{Binding Path=Age, Mode=TwoWay, ValidatesOnDataErrors=True}"/>
  7.     </StackPanel>
  8. </Window>
复制代码
  1. using System;
  2. using System.Windows;
  3. namespace WpfApp
  4. {
  5.     public partial class MainWindow : Window
  6.     {
  7.         public MainWindow()
  8.         {
  9.             InitializeComponent();
  10.             DataContext = new Person();
  11.         }
  12.     }
  13.     public class Person : IDataErrorInfo
  14.     {
  15.         private int _age;
  16.         public int Age
  17.         {
  18.             get { return _age; }
  19.             set
  20.             {
  21.                 _age = value;
  22.             }
  23.         }
  24.         public string Error
  25.         {
  26.             get { return null; }
  27.         }
  28.         public string this[string columnName]
  29.         {
  30.             get
  31.             {
  32.                 string error = null;
  33.                 if (columnName == "Age")
  34.                 {
  35.                     if (Age < 0 || Age > 120)
  36.                     {
  37.                         error = "Age must be between 0 and 120.";
  38.                     }
  39.                 }
  40.                 return error;
  41.             }
  42.         }
  43.     }
  44. }
复制代码
  1. <Window x:Class="WpfApp.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="WPF Data Binding Example">
  5.     <StackPanel>
  6.         <TextBox>
  7.             <TextBox.Text>
  8.                 <Binding Path=InputValue, Mode=TwoWay>
  9.                     <Binding.ValidationRules>
  10.                         <local:NumberValidationRule/>
  11.                     </Binding.ValidationRules>
  12.                 </Binding>
  13.             </TextBox.Text>
  14.         </TextBox>
  15.     </StackPanel>
  16. </Window>
复制代码
  1. using System;
  2. using System.Globalization;
  3. using System.Windows.Controls;
  4. namespace WpfApp
  5. {
  6.     public class NumberValidationRule : ValidationRule
  7.     {
  8.         public override ValidationResult Validate(object value, CultureInfo cultureInfo)
  9.         {
  10.             if (value is string input)
  11.             {
  12.                 int number;
  13.                 if (int.TryParse(input, out number))
  14.                 {
  15.                     return ValidationResult.ValidResult;
  16.                 }
  17.                 else
  18.                 {
  19.                     return new ValidationResult(false, "Please enter a valid number.");
  20.                 }
  21.             }
  22.             else
  23.             {
  24.                 return new ValidationResult(false, "Invalid input.");
  25.             }
  26.         }
  27.     }
  28. }
复制代码
六、高级数据绑定用法

(一)绑定到集合数据

  1. <Window x:Class="WpfApp.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="WPF Data Binding Example">
  5.     <StackPanel>
  6.         <ListBox ItemsSource="{Binding Path=People, Mode=OneWay}"/>
  7.     </StackPanel>
  8. </Window>
复制代码
  1. using System;
  2. using System.Collections.ObjectModel;
  3. using System.Windows;
  4. namespace WpfApp
  5. {
  6.     public partial class MainWindow : Window
  7.     {
  8.         public MainWindow()
  9.         {
  10.             InitializeComponent();
  11.             DataContext = new ViewModel();
  12.         }
  13.     }
  14.     public class ViewModel
  15.     {
  16.         public ObservableCollection<Person> People { get; set; } = new ObservableCollection<Person>();
  17.         public ViewModel()
  18.         {
  19.             People.Add(new Person { Name = "Alice", Age = 30 });
  20.             People.Add(new Person { Name = "Bob", Age = 35 });
  21.         }
  22.     }
  23.     public class Person
  24.     {
  25.         public string Name { get; set; }
  26.         public int Age { get; set; }
  27.     }
  28. }
复制代码
  1. <Window x:Class="WpfApp.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="WPF Data Binding Example">
  5.     <StackPanel>
  6.         <ListBox ItemsSource="{Binding Path=People, Mode=OneWay}">
  7.             <ListBox.ItemTemplate>
  8.                 <DataTemplate>
  9.                     <StackPanel>
  10.                         <TextBlock Text="{Binding Path=Name}"/>
  11.                         <TextBlock Text="{Binding Path=Age}"/>
  12.                     </StackPanel>
  13.                 </DataTemplate>
  14.             </ListBox.ItemTemplate>
  15.         </ListBox>
  16.     </StackPanel>
  17. </Window>
复制代码
  1. using System;
  2. using System.Collections.ObjectModel;
  3. using System.Windows;
  4. namespace WpfApp
  5. {
  6.     public partial class MainWindow : Window
  7.     {
  8.         public MainWindow()
  9.         {
  10.             InitializeComponent();
  11.             DataContext = new ViewModel();
  12.         }
  13.     }
  14.     public class ViewModel
  15.     {
  16.         public ObservableCollection<Person> People { get; set; } = new ObservableCollection<Person>();
  17.         public ViewModel()
  18.         {
  19.             People.Add(new Person { Name = "Alice", Age = 30 });
  20.             People.Add(new Person { Name = "Bob", Age = 35 });
  21.         }
  22.     }
  23.     public class Person
  24.     {
  25.         public string Name { get; set; }
  26.         public int Age { get; set; }
  27.     }
  28. }
复制代码
(二)绑定到 XML 数据

  1. <Window x:Class="WpfApp.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="WPF Data Binding Example">
  5.     <StackPanel>
  6.         <TreeView ItemsSource="{Binding Source={StaticResource xmlData}, XPath=/Root/Node}">
  7.             <TreeView.Resources>
  8.                 <XmlDataProvider x:Key="xmlData" Source="data.xml"/>
  9.             </TreeView.Resources>
  10.         </TreeView>
  11.     </StackPanel>
  12. </Window>
复制代码
(三)绑定到数据库数据

  1. <Window x:Class="WpfApp.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="WPF Data Binding Example">
  5.     <StackPanel>
  6.         <DataGrid ItemsSource="{Binding Path=Customers, Mode=OneWay}"/>
  7.     </StackPanel>
  8. </Window>
复制代码
  1. using System;
  2. using System.Windows;
  3. using WpfApp.DataAccess;
  4. namespace WpfApp
  5. {
  6.     public partial class MainWindow : Window
  7.     {
  8.         public MainWindow()
  9.         {
  10.             InitializeComponent();
  11.             DataContext = new ViewModel();
  12.         }
  13.     }
  14.     public class ViewModel
  15.     {
  16.         public ObservableCollection<Customer> Customers { get; set; }
  17.         public ViewModel()
  18.         {
  19.             using (var context = new MyDbContext())
  20.             {
  21.                 Customers = new ObservableCollection<Customer>(context.Customers);
  22.             }
  23.         }
  24.     }
  25.     public class Customer
  26.     {
  27.         public int Id { get; set; }
  28.         public string Name { get; set; }
  29.         public string Email { get; set; }
  30.     }
  31. }
复制代码
在这个示例中,Entity Framework(实体框架)被用于从数据库中检索数据并将其绑定到一个 “DataGrid”(数据表格)上。“ViewModel”(视图模型)类通过使用 “MyDbContext”(数据库上下文)查询数据库来初始化一个 “Customer”(客户)对象的 “ObservableCollection”(可观察集合)。
对象关系映射(ORM)与数据绑定:
像 Entity Framework 这样的对象关系映射工具简化了将数据库表映射到对象以及反向映射的过程。这使得将数据库数据绑定到 WPF 用户界面元素变得更加容易。当使用 ORM 时,对绑定对象所做的更改可以自动持久化回数据库,提供了无缝的数据绑定体验。
七、WPF 数据绑定的性能优化

(一)避免不必要的绑定更新

(二)优化集合绑定

(三)淘汰数据传输大小

八、结论

WPF 的数据绑定机制是一个强大的功能,使开发人员能够轻松创建动态且相应迅速的用户界面。通过理解数据绑定的概念和技术,包括绑定模式、数据验证以及高级用法场景,开发人员可以构建更高效、用户友爱的应用步伐。此外,优化数据绑定性能可以进一步提升 WPF 应用步伐的整体性能。凭借其灵活性和强大功能,WPF 数据绑定是当代应用步伐开发的宝贵工具。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4