110,569
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.ComponentModel;
namespace 学习WPF数据绑定 {
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window {
private NewTestData ntd;
private OldTestData otd;
public MainWindow() {
InitializeComponent();
ntd = new NewTestData() { txt = "新绑定" };
otd = new OldTestData() { txt = "旧绑定" };
//设定绑定
Binding bind1 = new Binding();
bind1.Source = ntd;
bind1.Path = new PropertyPath("txt");
textnew1.SetBinding(TextBox.TextProperty,bind1);
Binding bind2 = new Binding();
bind2.Source = otd;
bind2.Path = new PropertyPath("txt");
textold1.SetBinding(TextBox.TextProperty, bind2);
}
private void Button_Click(object sender, RoutedEventArgs e) {
textnew2.Text = ntd.txt;
textold2.Text = otd.txt;
}
}
//=====数据源class NewTestData
public class NewTestData:INotifyPropertyChanged {
private string _txt;
public string txt {
get { return _txt; }
set {
_txt = value;
if (PropertyChanged != null) {
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("txt"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
//=====数据源class OldTestData
public class OldTestData {
public string txt { get; set; }
}
}
<Window x:Class="学习WPF数据绑定.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="150" Width="200">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="35*"/>
<RowDefinition Height="35*"/>
<RowDefinition Height="48*"/>
</Grid.RowDefinitions>
<TextBlock Margin="10,5,163,10" Text="新" Grid.Row="0"/>
<TextBox Name="textnew1" Margin="34,5,87,6" Grid.Row="0"/>
<TextBox Name="textnew2" Margin="110,5,10,6" Grid.Row="0"/>
<TextBlock Margin="10,5,163,10" Text="旧" Grid.Row="1"/>
<TextBox Name="textold1" Margin="34,5,87,6" Grid.Row="1"/>
<TextBox Name="textold2" Margin="110,5,10,6" Grid.Row="1"/>
<Button Content="改变" Grid.Row="2" Margin="56,10" Click="Button_Click"/>
</Grid>
</Window>
private void Button_Click(object sender, RoutedEventArgs e)
{
//textnew2.Text = ntd.txt;
//textold2.Text = otd.txt;
ntd.txt = "hello";
otd.txt = "world";
}