读书人

WPF数据绑定为啥没反应

发布时间: 2013-08-27 10:20:47 作者: rapoo

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));


}
}
}


textbox1、textbox2的Text属性都绑定到一个Person对象,单击button的时候,修改了textbox1的Text属性值,因为Text属性是双向绑定吧,所以绑定源的Name属性值也会变的吧,而Name属性实现了INotifyPropertyChanged接口的,那textbox2也会跟着变的吧
可是,为什么textbox2的Text属性值没有变化呢?
[解决办法]
textbox1 的绑定中显式申明一下双向绑定(Mode=TwoWay),再试试看
[解决办法]
在确定有给定数据源的情况下这无非就两种问题,一就是二楼那个哥们说的数据双向绑定问题,另一个就是绑定数据源后没有及时刷新显示的问题(有的要控件要刷新,有的又不用刷新,要看是什么控件,我就遇到很多这问题,特别是第三方控件)
[解决办法]
textbox1 的绑定修改为
Text="{Binding Path=Name,UpdateSourceTrigger=PropertyChanged}" 

读书人网 >C#

热点推荐