1、binding源为非控件,而是C#类/实例
窗体(V)代码,
<Window x:Class="WpfBindingApp1.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:WpfBindingApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<TextBlock Width="160" Height="50" Text="年龄:" Margin="37,192,603,193" FontSize="20"/>
<TextBox Width="160" Height="50" x:Name="tb333" Text="{Binding person.Age}" Margin="134,173,506,212"/>
<TextBlock Width="160" Height="50" Text="姓名:" Margin="37,266,603,119" FontSize="20"/>
<TextBox Width="160" Height="50" x:Name="tb444" Margin="134,247,506,138" Text="{Binding person.Name}" />
<Button x:Name="btn111" Width="80" Height="60" Click="btn111_Click" Margin="360,299,360,76"/>
</Grid>
</Window>
C#后台(VM)代码,这里为了好看,可以把person类改名为xxViewModel
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
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 WpfBindingApp1
{
public partial class MainWindow : Window
{
public event PropertyChangedEventHandler PropertyChanged;
//要使用{ get; set; },令其作为属性,而不能是字段。
public PersonViewModel person { get; set; } = new PersonViewModel();
public MainWindow()
{
InitializeComponent();
person.Age = 10;
person.Name = "Tom";
this.DataContext = this; //如果这里this.DataContex=person,则界面上 binding直接绑person的属性即可,而不用带person.
}
private void btn111_Click(object sender, RoutedEventArgs e)
{
person.Age += 1;
person.Name += "+2" ;
}
}
public class PersonViewModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
private int _age;
public int Age
{
get { return _age; }
set
{
_age = value;
if (PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Age"));
}
}
}
}
}