2012-07-31 40 views
0

MainPage.xaml中
<TextBlock Text="{Binding Pathname, Source={StaticResource ViewModel}, Mode=OneWay}" />Silverlight TextBlock没有绑定到MVVM,我错过了什么?

的App.xaml

<ResourceDictionary> 
    <vm:InspectViewModel x:Key="ViewModel" /> 
</ResourceDictionary> 

视图模型

private string _pathname = null; 
public string Pathname 
{ 
    get { return _pathname; } 
    set 
    { 
     if (_pathname != value) 
     { 
      _pathname = value; 
      RaisePropertyChanged("Pathname"); 
     } 
    } 
} 

public void UpdatePathname(string path) 
{ 
    Pathname = path; 
} 

代码隐藏的MainPage

private void lazyNavTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) 
{   
    InspectViewModel vm = new InspectViewModel();   
    var path = view.GetPath().ToArray(); 
    string pathname = null; 
    // to figure out what the pathname is 
    for (int i = 0; i < path.Count(); i++) 
    { 
     TreeList treeItem = (TreeList)path[i].Key; 
     if (i == path.Count()-1) 
      pathname = pathname + treeItem.Name; 
     else 
      pathname = pathname + treeItem.Name + " : "; 
    } 
    vm.UpdatePathname(pathname); 
} 

绑定的TextBlock中显示什么,NAD a,zip。路径名shource正在改变,但是当我在更改时触发INotifyPropertyChanged事件时似乎没有发生任何事情。

我确定我错过了一些非常明显的东西,但我无法弄清楚什么!

回答

4

您正在创建您的视图模型的两个实例:

    在App.xaml中
  • (在应用程序资源,这是必然的实例)
  • 中的MainPage代码隐藏(InspectViewModel vm = new InspectViewModel(),这是修改后的实例)

,您应该使用单一实例你视图模型,例如,

var vm = (InspectViewModel)Application.Current.Resources["ViewModel"]; 

而不是在MainPage代码隐藏中创建它。

+0

+1,我错过了那部分... :) – 2012-07-31 11:31:06

+0

...课程!天才!我知道这是明显的。谢谢,问题解决了... – xhedgepigx 2012-07-31 11:42:45

0

看起来你刚刚错过了你的装订中的Path,试试;

Text="{Binding Path=Pathname, Source={StaticResource ViewModel}, Mode=OneWay}" 

编辑:显然,这是没有问题的,但保持这个答案,因为xhedgepigx提供如下评论有用的链接。

+0

不幸的是,事实并非如此。我已经尝试确保(并且仍然没有从我的TextBlock反应),但是您并不总是需要包含'Path ='[info](http://msdn.microsoft.com/zh-cn/library/cc189022 (v = vs.95).aspx)。谢谢 – xhedgepigx 2012-07-31 11:32:29

+0

在这种情况下,我可以确认'Path ='是可选的。 – jv42 2012-07-31 18:43:48

2

这是因为您在lazyNavTree_SelectedItemChanged中每次都从viewmodel创建一个实例。你应该只使用一个。

+0

+1作为接受类似的答案,但较少的信息,谢谢 – xhedgepigx 2012-07-31 11:43:19

相关问题