Xaml文件
<Window x:Class="BindApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<TextBox Text="{Binding HumanModel.Name, Mode=TwoWay}" Width="100" Height="30"/>
<Button Content="dianji" Width="100" Height="30" Margin="20,0,0,0" Click="Button_Click"/>
</StackPanel>
</Grid>
</Window>
界面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
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
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));
}
}
原文:https://www.cnblogs.com/EasonKing/p/14362445.html