我是wp7中双向绑定的新手。以下代码不会自动将文本框值分配给对象并返回null。
的Xaml:
<Grid x:Name="ContentPanel" DataContext="{Binding usd}" Grid.Row="1" Margin="14,10,10,-10" >
<TextBox Text="{Binding UserName,Mode=TwoWay}" Name="txt1" Width="200" Height="60" FontSize="20" Margin="128,48,128,499"/>
<TextBox Text="{Binding Password,Mode=TwoWay}" Name="txt2" Width="200" Height="60" FontSize="20" Margin="128,263,128,284"/>
<TextBox Text="{Binding Email,Mode=TwoWay}" Name="txt3" Width="200" Height="60" FontSize="20" Margin="128,159,128,388"/>
<Button Content="Send" FontSize="18" Margin="179,413,170,129"
Click="Button_Click_1" />
</Grid>
CS:
public class UserLogin:INotifyPropertyChanged
{
private string _username;
private string _pwd;
private string _email;
public string UserName
{
get
{
return _username;
}
set
{
_username = value;
OnPropertyChanged("UserName");
}
}
public string Password
{
get
{
return _pwd;
}
set
{
_pwd = value;
OnPropertyChanged("Password");
}
}
public string Email
{
get
{
return _email;
}
set
{
_email = value;
OnPropertyChanged("Email");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
实例化
public UserLogin usd = null;
在构造函数中:
usd = new UserLogin();
按钮ClickEvent:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
// ContentPanel.DataContext = usd;
MessageBox.Show(usd.Email);
}
消息框语句中的空引用异常。感谢..
答案 0 :(得分:1)
你可以绑定到公共属性 - 所以你的:DataContext =“{Binding usd}”应该是错的,因为usd只是一个字段
顺便说一句,如果你也在你的ctor中设置了这个,那么删除它可以工作的xaml绑定
usd = new UserLogin();
ContentPanel.DataContext = usd;
答案 1 :(得分:0)
关于您的控件/页面(XAML属于它)
答案 2 :(得分:0)
因为你的usd没有设置为属性而只是变量....做一件事
public UserLogin usd {get;set;}
usd = null;