2012-04-01 58 views
0

我爲我的主視圖模型創建了一個屬性「IsLoading」。這個想法是,只要此屬性設置爲true,就會顯示一個進度條。到目前爲止這麼好複合材料綁定到屬性和內部viewmodel屬性未觸發

這個問題是,我有一個命令,調用另一個viewmodel(代碼在那裏,因爲它是來自另一個頁面的功能,但我希望能夠從我的主viewmodel )

所以,我繼續修改的主要屬性是這樣的:

public const string IsLoadingPropertyName = "IsLoading"; 

     private bool _isLoading; 

     public bool IsLoading 
     { 
      get 
      { 
       return _isLoading || ((ViewModelLocator)Application.Current.Resources["Locator"]).SettingsViewModel.IsLoading; 
      } 
      set 
      { 
       if (value != _isLoading) 
       { 
        _isLoading = value; 
        RaisePropertyChanged(IsLoadingPropertyName); 
       } 
      } 
     } 

和XAML

<shell:SystemTray.ProgressIndicator> 
     <shell:ProgressIndicator IsIndeterminate="true" IsVisible="{Binding Main.IsLoading, Source={StaticResource Locator}}" /> 
    </shell:SystemTray.ProgressIndicator> 

所以,我說,主視圖模型正在加載,或者設置視圖模型正在加載。 問題是綁定僅在設置主視圖模型的IsLoading屬性時才起作用,當它在內部IsLoading屬性中設置時,它不起作用。兩者都具有相同的屬性名稱「IsLoading」。不應該被發現?

例如,在主視圖模型(只是爲了簡單的命令執行):

private void ExecuteRefreshCommand() 
    { 
     ViewModelLocator viewModelLocator = Application.Current.Resources["Locator"] as ViewModelLocator; 
     viewModelLocator.SettingsViewModel.GetCurrentLocationCommand.Execute(null); 
    } 

和裏面設置瀏覽模式:

public RelayCommand GetCurrentLocationCommand 
     { 
      get 
      { 
       Action getLocation =() => 
       { 
        if (!NetworkInterface.GetIsNetworkAvailable()) 
        { 
         return; 
        } 

        var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default); 
        watcher.PositionChanged += WatcherPositionChanged; 
        IsLoading = true; // settings view model "IsLoading" propertychanged raising property 
        watcher.Start(); 
       }; 
       return new RelayCommand(getLocation); 
      } 
     } 

回答

0

你看MainViewModel的isLoading屬性確定是否顯示進度條。 Silverlight使用NotifyPropertyChanged事件來確定它應該何時重新評估某個屬性。設置SettingsViewModel的IsLoading屬性或MainViewModel的屬性時,只會爲該ViewModel引發changedEvent。你應該爲兩者提高ChangedEvent。

一種改進的二傳手例子可能是(根據公開的方法)

set 
{ 
    if (value != _isLoading) 
    { 
     _isLoading = value; 
     RaisePropertyChanged(IsLoadingPropertyName); 
     ((ViewModelLocator)Application.Current.Resources["Locator"]).SettingsViewModel.RaisePropertyChanged(IsLoadingPropertyName); 
    } 
} 

注意,很多MVVM框架提供了一個名爲消息功能,是理想的做跨視圖模型通信,而無需創建創建權的嚴格依賴現在。或者,您可以使用全局使用的IsLoading屬性。

+0

我明白了。使其工作,但它是相反的方式(從設置viewmodel提高主視圖模型 – 2012-04-01 10:10:51