使用MVVM模式进行WPF开发,数据绑定问题
问题如下:
我将MainViewModel设置成MainWindow的DataContext,这个时候修改用户名代表的TextBox,此时不会调用MainViewModel.cs中的
set,而是调用
{
if (userinfo == value)
{
return;
}
userinfo = value;
RaisePropertyChanged("UserInfo");
}
public class User中的Set方法,但是为什么会通知界面进行更新呢?
{
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
}
<TextBlock Grid.Column="0" Grid.Row="0" Text="用户名:"></TextBlock>
<TextBox Grid.Column="1" Grid.Row="0">
<TextBox.Text>
<Binding Path="UserInfo.Name" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
<Binding.ValidationRules>
<!--<ExceptionValidationRule />-->
<local:UserValidate ValidateType="UserName" ></local:UserValidate>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
private User userinfo;
/// <summary>
/// Sets and gets the UserInfo property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public User UserInfo
{
get
{
return userinfo;
}
set
{
if (userinfo == value)
{
return;
}
userinfo = value;
RaisePropertyChanged("UserInfo");
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
}
[解决办法]
<StackPanel>
<TextBox Width="70" Text="{Binding Path=Userinfo.Name,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"/>
<TextBox Width="70" Text="{Binding Path=Userinfo.Name,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"/>
</StackPanel>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new VM();
}
}
public class VM : INotifyPropertyChanged
{
private User userinfo;
/// <summary>
/// Sets and gets the UserInfo property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public User UserInfo
{
get
{
return userinfo;
}
set
{
if (userinfo == value)
{
return;
}
userinfo = value;
PropertyChanged(this, new PropertyChangedEventArgs("UserInfo"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
}