2012-04-01 47 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

相关问题