【发布时间】:2013-11-28 22:54:55
【问题描述】:
我有一个遵循 MVVM 方案的应用程序。我有多个视图和视图模型。 在我的主页上,我有一个文本块,我想用来自所选元素的信息进行更新。
在启动应用程序时,我从 mainviewmodel 插入一个值来测试绑定,以便一切正常。其中代码如下:
<TextBlock Text="{Binding colorOfElement}" Grid.Row="1"/>
主视图模型中的代码
private string _colorOfElement;
public string colorOfElement
{
get
{
return _colorOfElement;
}
set
{
_colorOfElement = value;
NotifyPropertyChanged("colorOfElement");
}
}
......
colorOfElement = "Test";
这显示正确。当用户随后与元素交互时,会在新视图模型中触发一个事件,在这里我有一个对主视图模型的引用,因此我可以轻松更新字符串 colorOfElement。
private MainViewModel mv;
......
public void MouseDown(ManipulationStartedEventArgs obj)
{
FrameworkElement MovingElement = (FrameworkElement)obj.OriginalSource;
Canvas canvas = FindParentOfType<Canvas>(MovingGear);
obj.ManipulationContainer = canvas;
obj.Handled = true;
testViewModel viewModel = (testViewModel)MovingElement.DataContext;
mv.colorOfElement = viewModel.model.Color;
}
当这个函数执行时,我被发送到 mainviewmodel 并且 NotifyPropertyChanged 被触发。但是在显示视图的 Application.Page 上,我看不到变量的任何更新,但在代码中变量发生了变化。对这个绑定问题有什么想法吗?
回答 当我测试了数据上下文并且一切正常时,问题出在我的公开课上。
public class MainViewModel : ViewModelBase
这里它应该包含 INotifyPropertyChanged 接口以启用该功能。所以简单的解决方案是添加这个并获取:
public class MainViewModel : ViewModelBase, INotifyPropertyChanged
那你可以走了:)
【问题讨论】:
-
在我看来,视图没有收到 NotifyPropertyChanged。您确定将 MainViewModel 设置为要更新的 View 的 DataContext 吗?
-
我已经在视图中设置了DataContext,这使我可以在启动时设置变量。我同意它没有收到,但我不知道为什么。
标签: c# mvvm binding windows-phone-8