数据绑定的基本步骤:
(1)先声明一个类及其属性
(2)初始化类赋值
(3)在C#代码中把控件DataContext=对象;
(4)在界面设计里,控件给要绑定的属性{Binding 绑定类的属性}
原理:监听事件机制,界面改变有TextChanged之类的事件,所以改变界面可以同步修改到对象
想让普通对象实现数据绑定,需要实现INotifyPropertyChanged接口才能监听ProperChanged。具体代码如下显示:
- class Person:INotifyPropertyChanged
- {
- private int age;
- public int Age
- {
- get
- {
- return age;
- }
- set
- {
- this.age = value;
- if (PropertyChanged != null)
- {
- PropertyChanged(this,
- new PropertyChangedEventArgs("Age"));
- }
- }
- }
- }
BindingMode枚举值
MainWindow.xaml
- <Window x:Class="WpfApp1.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:WpfApp1"
- mc:Ignorable="d"
- Title="MainWindow" Height="600" Width="800">
- <StackPanel>
- <TextBlock Text="Student ID:" FontWeight="Bold" Margin="5"/>
- <TextBox Name="textBoxId" Margin="5" Text="{Binding Id,Mode=TwoWay}"/>
- <TextBlock Text="Student Name:" FontWeight="Bold" Margin="5"/>
- <TextBox Name="textBoxName" Margin="5" Text="{Binding Name,Mode=TwoWay}"/>
- <TextBlock Text="Student List:" FontWeight="Bold" Margin="5"/>
- <ListBox Name="listBox1" Height="110" Margin="5" >
- <ListBox.ItemTemplate>
- <DataTemplate>
- <StackPanel Orientation="Horizontal">
- <TextBlock Text="{Binding Path=Id}" Width="30"/>
- <TextBlock Text="{Binding Path=Name}" Width="60"/>
- <TextBlock Text="{Binding Path=Age}" Width="30"/>
- </StackPanel>
- </DataTemplate>
- </ListBox.ItemTemplate>
- </ListBox>
- <ListBox Name="listBox2" Height="80" ItemsSource="{Binding Student}" DisplayMemberPath="Id" Margin="5"/>
- <Slider Name="slider1" MinHeight="25" Value="{Binding Id}"/>
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="*"></RowDefinition>
- </Grid.RowDefinitions>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="*"/>
- <ColumnDefinition Width="*"/>
- </Grid.ColumnDefinitions>
- <Button Grid.Column="0" Content="Action" FontSize="40" Name="btnCtrl1" Height="80" Margin="5" Click="BtnCtrl1_Click"/>
- <Button Grid.Column="1" Content="Action" FontSize="40" Name="btnCtrl2" Height="80" Margin="5" Click="BtnCtrl2_Click"/>
- </Grid>
- </StackPanel>
- </Window>
首先解释下C#中的Task.Delay()和Thread.Sleep()
MainWindow.xaml.cs
- using System;
- using System.Collections.ObjectModel;
- using System.ComponentModel;
- using System.Threading.Tasks;
- using System.Windows;
- namespace WpfApp1
- {
- /// <summary>
- /// MainWindow.xaml 的交互逻辑
- /// </summary>
- public partial class MainWindow : Window
- {
- public ObservableCollection<Student> stuList;
- public MainWindow()
- {
- InitializeComponent();
- this.DataContext = new Student() { Name="111", Id =1 };
- Task.Run(async() => //开启异步线程task
- {
- await Task.Delay(3000); //延时3秒
- Dispatcher.Invoke((Action)delegate //线程中主界面显示需要用委托,不然这次赋值,在界面不更新
- {
- this.DataContext = new Student() { Name = "222", Id = 2 };
- });
- });
- this.DataContext = new Student() { Name = "333" , Id = 3 };
- }
- private void BtnCtrl1_Click(object sender, RoutedEventArgs e)
- {
- Student stu = new Student() { Id = 4, Name = "Jon", Age = 29 }; //实例化一个Student类 并给类成员赋值
- this.DataContext = stu;//将实例化得对象传给DataContext
- }
- private void BtnCtrl2_Click(object sender, RoutedEventArgs e)
- {
- ObservableCollection<Student> stuList = new ObservableCollection<Student>() //具有通知属性的list
- {
- new Student() { Id=5, Name="Tim", Age=29 },
- new Student() { Id=6, Name="Tom", Age=28 },
- };
- this.listBox1.ItemsSource = stuList;
- this.listBox2.ItemsSource = stuList;
- this.listBox2.DisplayMemberPath = "Name";
- this.DataContext = stuList;
- }
- }
- public class Student : INotifyPropertyChanged //创建一个继承自INotifyPropertyChanged的类Student
- {
- private string name;
- public string Name
- {
- get { return name; }
- set
- {
- name = value;
- if (this.PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs("Name")); //给Name绑定属性变更通知事件
- }
- }
- }
- private int id;
- public int Id
- {
- get { return id; }
- set
- {
- id = value;
- if (this.PropertyChanged != null)
- {
- this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Id"));//给Id绑定属性变更通知事件
- }
- }
- }
- private int age;
- public int Age
- {
- get { return age; }
- set
- {
- age = value;
- if (this.PropertyChanged != null)
- {
- this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Age"));//给Age绑定属性变更通知事件
- }
- }
- }
- public int ID { get; internal set; }
- public event PropertyChangedEventHandler PropertyChanged;
- }
- }
本文转载自微信公众号「CSharp编程大全」,可以通过以下二维码关注。转载本文请联系CSharp编程大全公众号。