Xaml文件
界面Cs文件
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;
namespace BindApp{ /// /// MainWindow.xaml 的交互逻辑 /// public partial class MainWindow : Window { public HumanViewModel viewModel; int a = 0; public MainWindow() { InitializeComponent(); viewModel = new HumanViewModel(); this.DataCOntext= viewModel; }
private void Button_Click(object sender, RoutedEventArgs e) { viewModel.SetModel("数字是" + a.ToString()); a++; } }}
ViewModel文件
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;
namespace BindApp{ public class HumanViewModel { private Human humanModel = new Human();
public Human HumanModel { get { return humanModel; } set { humanModel = value; } }
public void SetModel(string name) { humanModel.Name = name; } }}
这里要注意Human类的实例需要以属性的形式定义,如果是字段的话绑定会失败,原因未知
Human文件
using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;
namespace BindApp{ public class Human : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string name; public string Name { get { return name; } set { name = value; if (PropertyChanged != null) {PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } }
}}
这里使用了INotifyPropertyChanged接口实现通知UI变化,也可以直接继承DependencyObject的方式实现,依赖对象和依赖属性天然自带变化通知功能
using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;
namespace BindApp{ public class Human : DependencyObject { public string Name { get { return (string)GetValue(NameProperty); } set {SetValue(NameProperty, value);} }
public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Human)); }}