【发布时间】:2011-06-14 02:04:57
【问题描述】:
我正在尝试使用 Silverlight 学习 MVVM 模式。有大量的视频和博客。我在高层次上理解它,但似乎无法自己实现它。
我得到了以下视图:
<UserControl x:Class="SilverlightApplication1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:SilverlightApplication1.ViewModel"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="{Binding Name, Mode=TwoWay}" Width="200" Height="200"/>
<Button Name="btn1" Width="200" Height="20" Margin="100,268,100,12" Click="btn1_Click"/>
</Grid> </UserControl>
在我的虚拟机中,我有: 命名空间 SilverlightApplication1.ViewModel
{
public class ViewModel : INotifyPropertyChanged
{
private Model.UserModel m_model;
public ViewModel()
{
m_model = new Model.UserModel();
}
public string Name
{
get
{
return m_model.Name;
}
set
{
if (value != m_model.Name)
{
m_model.Name = value;
InvokePropertyChanged("Name");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void InvokePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
在我的模型中:
namespace SilverlightApplication1.Model
{
public class UserModel
{
public string Name { get; set; }
}
}
基本上,我想模拟按钮单击并更新属性,以便它可以触发属性更改事件。我试着像这样在 MainPage 代码后面的属性上硬编码:
private void btn1_Click(object sender, RoutedEventArgs e)
{
ViewModel.ViewModel vm = new ViewModel.ViewModel();
vm.Name = "Test";
}
是否应该更新属性(对于名称)并引发 propertychanged 事件?我见过其他例子做类似的事情。我不明白什么是订阅事件
任何人都可以发光吗?
【问题讨论】:
-
表面上看起来不错,但是,您是否设置断点或进行了任何故障排除?你的发现是什么?运行应用程序时会发生什么?除了你的 NotifyPropertyChange 一切正常?
-
PropertyChanged 事件始终为 Null。当我为属性设置断点时,它会更新,但是事件永远不会引发
标签: silverlight mvvm