环境是vs2010+wpf 4.0
相关代码如下(插入代码后会失去格式,试过几次均如此):
<Page x:Class="WpfBrowserApplication1.Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" Title="Page1"> <Grid> <TextBox Height="23" HorizontalAlignment="Left" Margin="59,69,0,0" Name="textBox1" VerticalAlignment="Top" Width="176"/> <Button Content="Button1" Height="23" HorizontalAlignment="Left" Margin="105,0,0,90" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click" /> <Button Content="Button2" Height="23" HorizontalAlignment="Left" Margin="206,187,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="button2_Click" /> <Button Content="Button3" Height="23" HorizontalAlignment="Left" Margin="16,187,0,0" Name="button3" VerticalAlignment="Top" Width="75" Click="button3_Click" /> </Grid></Page>
namespace WpfBrowserApplication1{ /// <summary> /// Interaction logic for Page1.xaml /// </summary> public partial class Page1 : Page { public sub s { get; set; } public Page1() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { s = new sub(); Binding b = new Binding(); b.Path = new PropertyPath("Name"); b.Source = s; b.Mode = BindingMode.TwoWay; textBox1.SetBinding(TextBox.TextProperty, b); s.Name = "init"; } private void button2_Click(object sender, RoutedEventArgs e) { textBox1.Text = "button2"; MessageBox.Show(s.Name); } private void button3_Click(object sender, RoutedEventArgs e) { s.Name = "button3"; MessageBox.Show(textBox1.Text); } } public class sub { public string Name { get; set; } }}
在通过单击button1绑定后,不论是修改源数据还是目标对象数据,都不能同步。