日期:2014-05-17  浏览次数:20984 次

WPF,数据绑定为什么没反应

<Window.Resources>
    <local:Person x:Key="mydatasource" Name="张三" ></local:Person>
</Window.Resources>
<Grid HorizontalAlignment="Left" Height="289" VerticalAlignment="Top" Width="533" DataContext="{StaticResource mydatasource}">
    <TextBox Name="textbox1" Text="{Binding Path=Name}" HorizontalAlignment="Left" Height="23" Margin="120,131,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <Button Content="Button" HorizontalAlignment="Left" Height="29" Margin="275,164,0,0" VerticalAlignment="Top" Width="76" Click="Button_Click"/>
    <TextBox Name="textbox2" HorizontalAlignment="Left" Height="23" Margin="120,192,0,0" TextWrapping="Wrap" Text="{Binding Path=Name}" VerticalAlignment="Top" Width="120"/>        
</Grid>


private void Button_Click(object sender, RoutedEventArgs e)
{
    textbox1.Text = "李四";
}


 class Person : INotifyPropertyChanged  
    {
        public event PropertyChangedEventHandler PropertyChanged; 

        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                OnPropertyChanged("Name"); 
            }
        }
        protected void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));