WPF双向数据绑定总结

参考官方:https://docs.microsoft.com/zh-cn/dotnet/framework/wpf/data/data-binding-wpf

实例程序:https://files.cnblogs.com/files/sntetwt/WPFBinding.zip

1、指定绑定源

WPF双向数据同步:目标属性(UI)和源属性(CS)数据同步。

实现双向数据同步数据源需要实现依赖属性INotifyPropertyChanged接口,因为依赖属性有垂直的内嵌变更通知机制。

INotifyPropertyChanged是用于实现界面通知。
DependencyObject是实现依赖对象的依赖属性。

名空间:

using System.ComponentModel;

实现依赖属性INotifyPropertyChanged接口

using System;
using System.ComponentModel;

namespace WPFBinding
{
    /// <summary>
    /// 实现INotifyPropertyChanged接口
    /// </summary>
    public class Users : INotifyPropertyChanged
    {
        /// <summary>  
        /// 姓名  
        /// </summary>  
        private string _Name;
        public string Name
        {
            get
            {
                return _Name;
            }
            set
            {
                _Name = value;
                OnPropertyChanged("Name");
            }
        }
        /// <summary>  
        /// Email  
        /// </summary>  
        private string _Email;
        public string Email
        {
            get
            {
                return _Email;
            }
            set
            {
                _Email = value;
                OnPropertyChanged("Email");
            }
        }
        protected internal virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

2、MVVM架构,ViewModel初始化

namespace WPFBinding
{
    public class ViewModel
    {
        public Users user { get; set; }
        public ViewModel()
        {
            this.user = new Users();
        }
    }
}

3.1、交互逻辑,实例化数据(方式一)

using System;
using System.Windows;

namespace WPFBinding
{
    /// <summary>
    /// MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public ViewModel viewModel;
        public MainWindow()
        {
            InitializeComponent();
            this.viewModel = new ViewModel();
            this.Loaded += (s, e) =>
            {
                this.DataContext = viewModel;
                this.viewModel.user = new Users()
                {
                    Name = "杨秀徐",
                    Email = "471812366@qq.com"
                };
            };
        }
    }
}

3.2、XAML绑定数据(方式一)

<TextBox Name="txtName" Text="{Binding user.Name}"></TextBox>
<TextBox Name="txtEmail" Text="{Binding user.Email}"></TextBox>

  

  

4.1、交互逻辑,实例化数据(方式二)

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace WPFBinding
{
    /// <summary>
    /// GetBinding.xaml
    /// </summary>
    public partial class GetBinding : Window
    {
        public ViewModel viewModel;
        public GetBinding()
        {
            InitializeComponent();
            this.viewModel = new ViewModel();
            this.Loaded += (s, e) =>
            {
                this.DataContext = viewModel;
                this.viewModel.user = new Users()
                {
                    Name = "杨秀徐",
                    Email = "471812366@qq.com"
                };
                //绑定依赖属性Name
                txtName.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = viewModel.user });
                //绑定元素属性Text
                lblName.SetBinding(ContentProperty, new Binding("Text") { Source = txtName });
                //绑定依赖属性Email
                txtEmail.SetBinding(TextBox.TextProperty, new Binding("Email") { Source = viewModel.user });
                //绑定元素属性Text
                lblEmail.SetBinding(ContentProperty, new Binding("Text") { Source = txtEmail });
            };
        }
    }
}

4.2、XAML元素(方式二)  

<Label Name="lblName"></Label>
<TextBox Name="txtName"></TextBox>
<Label Name="lblEmail"></Label>
<TextBox Name="txtEmail"></TextBox>

 5.1、Binding对象的属性说明

属性名                 描述        
1、Converter:转换器,将绑定的内容转换成自己需要的内容。自定义转换类 必须继承于:IValueConverter接口
2、ElementName:绑定的源对象,本人理解 专程用于UI控件之间属性的绑定
3、FallbackValue :绑定无法返回有效值时的默认显示值
4、Mode:绑定方式,枚举类型 Default OneWay TwoWay OneTime OneWayToSource
5、Path:属性 路径,用来指定要绑定数据源的路径,其性质是一个属性,该属性该当是依靠属性,也即便能够告终积极更新机制的【单个类实现INotifyPropertyChanged、集合要 实现INotifyCollectionChanged接口】
6、RelativeSource:常用于自身绑定或者数据模板中来指定绑定的源对象及控件模块中的绑定。
7、Source:源对象,控件或自定义对象等。
8、StringFormat:格式化表达式
9、UpdateSourceTrigger:在双向绑定时TwoWay 或 OneWayToSource 时。用来确定属性更改的时机。UpdateSourceTrigger枚举类型:Default,PropertyChanged,LostFocus,Explicit。
10、ValidationRules:验证规则.可以被设置为一个或多个派生自ValidationRule的对象,每个规则都会检查特定的条件并更具结果来标记数据的有效性

5.2、Mode指定绑定的方向

数据绑定模式共有四种:OneTime、OneWay、OneWayToSource和TwoWay,默认是TwoWay。

TwoWay 当发生更改时的目标属性或源属性更新目标属性。
OneWay 仅当源属性更改时,请更新目标属性。
OneTime 仅当应用程序启动时或时,请更新目标属性DataContext发生了更改。
OneWayToSource 目标属性更改时,请更新源属性。
Default 默认值将导致Mode要使用的目标属性的值。

5.3、UpdateSourceTrigger    四种用来确定属性更改的时机,对于 Model=TwoWay 及 OneWayToSource是源数据改变时机。

6、UI属性绑定数据对象。

6.1 、UI属性直接绑定实例对象 。实例:Text="{Binding Path=EntryDate, StringFormat=yyyy-MM-dd}"

6.2 、UI属性直接绑定静态对象。实例:DataContext="{x:Static local:GlobalData.user}"

6.3 、UI属性绑定资源中的对象。DataContext="{StaticResource ResourceKey=userKey}"

7、清除绑定

BindingOperations.ClearBinding(txtBlock, TextBlock.TextProperty);

8、集合双向绑定
WPF 提供 ObservableCollection<T> 类,它是实现 INotifyCollectionChanged 接口的数据集合的内置实现。

public class Users : ObservableCollection<Users>
{
    public Users() : base()
    {
            
    }
}

  

  

原文地址:https://www.cnblogs.com/sntetwt/p/9942528.html