读书人

使用MVVM模式进行WPF开发数据绑定有

发布时间: 2013-08-06 16:47:25 作者: rapoo

使用MVVM模式进行WPF开发,数据绑定问题
问题如下:
我将MainViewModel设置成MainWindow的DataContext,这个时候修改用户名代表的TextBox,此时不会调用MainViewModel.cs中的

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; }
}
中的Set方法,但是为什么会通知界面进行更新呢?
User.cs并没有实现INotifiPropertyChange接口,而且也不会调用MainViewModel.cs中的Set方法。
希望各位大神指导下,为什么只调用了User.cs的set方法,却也通知了界面进行更新?



MainWindow.xaml

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



MainViewModel.cs
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");
}
}


User.cs
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; }
}







另外一个没有更新.....
同学 你是不是代码写错了

读书人网 >C#

热点推荐