前台页面:
<Window x:Class="WPFTest.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" Loaded="Window_Loaded"> <Grid Name="gdTest"> <Grid.RowDefinitions> <RowDefinition Height="30"/> <RowDefinition Height="30"/> <RowDefinition Height="30"/> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Orientation="Horizontal" > <TextBlock Width="80" TextAlignment="Right" VerticalAlignment="Center" >测试1:</TextBlock> <TextBox Width="100" VerticalAlignment="Center" Text="{Binding Path=Test1}" Name="txtTest1" ></TextBox> </StackPanel> <StackPanel Grid.Row="1" Orientation="Horizontal" > <TextBlock Width="80" TextAlignment="Right" VerticalAlignment="Center" >测试2:</TextBlock> <TextBox Width="100" VerticalAlignment="Center" Text="{Binding Path=Test2}" Name="txtTest2" ></TextBox> </StackPanel> <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" > <Button Height="30" Width="80" Name="btnTest" Click="btnTest_Click" Margin="0,0,5,0" >确定</Button> </StackPanel> </Grid> </Window>
后台代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; 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 WPFTest { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public Tset test = new Tset(); private void btnTest_Click(object sender, RoutedEventArgs e) { test.Test1 = "111111"; test.Test2 = "222222"; } private void Window_Loaded(object sender, RoutedEventArgs e) { gdTest.DataContext = test; } } }
绑定的实体类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace WPFTest { public class Tset : INotifyPropertyChanged { [field: NonSerializedAttribute()] public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } private string _test1; public string Test1 { get { return _test1; } set { if (_test1 != value) { _test1 = value; NotifyPropertyChanged("Test1"); } } } public string Test2 { get; set; } } }