C# InotifyProperty在singleton中更改并绑定到WPF元素

C# InotifyProperty在singleton中更改并绑定到WPF元素,c#,wpf,mvvm,binding,C#,Wpf,Mvvm,Binding,我再次尝试使用MVVM,目前我的代码遇到两个问题首先让我解释一下代码结构: 我有这样一门课(当然是简化的): 以及从该基类继承的单例: public class NavigationService : NavigationServiceBase { private static readonly INavigationService _instance = new NavigationService(); public static INavigationService Inst

我再次尝试使用MVVM,目前我的代码遇到两个问题
首先让我解释一下代码结构:

我有这样一门课(当然是简化的):

以及从该基类继承的单例:

public class NavigationService : NavigationServiceBase
{
    private static readonly INavigationService _instance = new NavigationService();
    public static INavigationService Instance { get { return _instance; } }

    ...
}
视图模型:

private INavigationService _navigationService;

public IView CurrentView { get { return _navigationService.CurrentView; } }
public ICommand NavigateCommand { get; private set; }

public MainWindowViewModel()
{
    _navigationService = NavigationService.Instance;
    NavigateCommand = new RelayCommand(param => Navigate(param));
}

private void Navigate(object requestedPage)
{
    _navigationService.Navigate((string)requestedPage);
    //OnPropertyChanged("CurrentView"); // this works , but...
}
public IView CurrentView { get { return _navigationService.CurrentView; } }
现在是问题:
1.)我正在Visual Studio 2012 Express中编辑XAML。它似乎可以工作,但我收到一条警告消息:
无法加载一个或多个请求的类型。检索LoaderExceptions以获取更多信息。
当我声明用于绑定ViewModel的资源时,它显示在部分中。这是什么意思?如果我摆脱单身汉,信息就会消失。无论采用哪种方式,Project都可以正常编译和运行


2.)我的OnPropertyChanged(“CurrentView”)似乎没有启动或其他功能,因为我必须从ViewModel本身中手动调用此方法。如果我从基类或从继承单例尝试它,它就不起作用。(绑定只会忽略新值)。如果我在处理命令时手动执行此操作,它会工作。是的,这只是一行额外的代码,但我想知道,有没有一种方法可以让它在没有像这样的“欺骗”的情况下工作?

问题是您绑定到ViewModel中的属性:

private INavigationService _navigationService;

public IView CurrentView { get { return _navigationService.CurrentView; } }
public ICommand NavigateCommand { get; private set; }

public MainWindowViewModel()
{
    _navigationService = NavigationService.Instance;
    NavigateCommand = new RelayCommand(param => Navigate(param));
}

private void Navigate(object requestedPage)
{
    _navigationService.Navigate((string)requestedPage);
    //OnPropertyChanged("CurrentView"); // this works , but...
}
public IView CurrentView { get { return _navigationService.CurrentView; } }
NatigationService
正在引发
PropertyChanged
,但这发生在
\u navigationService
中,而不是在ViewModel本身中,因此视图从未看到该事件

有两种常见的选择:

您可以在导航服务上侦听
PropertyChanged
事件,并在需要时处理在本地引发该事件:

_navigationService = NavigationService.Instance;
_navigationService.PropertyChanged += (o,e) => 
{
   // When navigation raises prop changed for this property, raise it too
   if (e.PropertyName == "CurrentView")
     OnPropertyChanged("CurrentView");
}; 
NavigateCommand = new RelayCommand(param => Navigate(param));
另一种选择是公开服务,并直接绑定到它:

public INavigationService Navigation { get { return _navigationService; } }
然后,在您的视图中,绑定到服务内部的内容,而不是本地属性:

<ContentPresenter Content="{Binding Navigation.CurrentView}" />

啊,我明白了。有道理:)谢谢。我自己找出了第一个“问题”的原因,显然这只是一件愚蠢的事情。我试图在构造函数中进行一些反射,试图检查当前程序集,这显然在设计应用程序时失败了。。。。。