# WPF Databinding的几种方式

gray and brown mountain

WPF Databinding的几种方式

有时候会和UWP、其他语言的绑定弄混,这里做一下备份记录

两种情况,一种使用viewmodel,一种直接绑定。

一、直接绑定

要绑定的对象(比如page、Window)直接实现INotifyPropertyChanged接口,如下例子:

 public partial class LoginPage : Page, INotifyPropertyChanged
{
        bool SettingsShow = false;


        private string intvalue = "aaa";//私有

        public event PropertyChangedEventHandler? PropertyChanged;

        public string IntValue
        {
            get { return intvalue; }//获取值时将私有字段传出;
            set
            {
                intvalue = value;//赋值时将值传给私有字段
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IntValue"));//一旦执行了赋值操作说明其值被修改了,则立马通过INotifyPropertyChanged接口告诉UI(IntValue)被修改了
            }
        }

        public LoginPage()
        {
            InitializeComponent();
            DataContext= this;
        }
}

在布局文件中标注:

 d:DataContext="{d:DesignInstance Type=local:LoginPage}"

就可以直接使用类似 Text="{Binding IntValue}"这样的方式绑定了

二、使用viewmodel

使用mvvm库 Nuget安装CommunityToolkit.Mvvm

public class TicketSaleViewmodel : ObservableRecipient
{

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public bool IsMember { get; set; }
    }

    public string a = "asd";

    public string A
    {
        get { return a; }
        set { a = value; OnPropertyChanged(nameof(A));}
    }

    private ObservableCollection<YourBean> _myBeans = new ObservableCollection<YourBean>(){};

    public ObservableCollection<YourBean> MyBeans
    {
        get { return _myBeans;}
        set { _myBeans = value; OnPropertyChanged(nameof(MyBeans));}
    }
}