0
我懷疑這個行爲有一個術語,如果我知道它,我可以谷歌它並學習我需要什麼。但是,我不知道。對象一旦構造函數完成就會消失
這裏是我的構造函數:
[Export(typeof(MainWindowViewModel))]
public class MainWindowViewModel : ObservableObject
{
private readonly IProductService _productService;
private readonly IProfileService _profileService;
public IEnumerable<ProductViewModel> Products { get; private set; }
private ProductViewModel _productSelected;
[ImportingConstructor]
public MainWindowViewModel(IProductService productService, IProfileService profileService, ILoggingService logger)
{
Products = _productService.InstalledProducts.Select(p => new ProductViewModel(p, _profileService, _logger));
SelectTheProductInDirectoryRunningFrom();
_productSelected.Load();
}
protected virtual void SelectTheProductInDirectoryRunningFrom()
{
string currentDir = Directory.GetCurrentDirectory();
if (_productSelected != null && _productSelected.InstalledPath != null &&
!_productSelected.InstalledPath.Contains(currentDir))
{
_productSelected =
Products.Where(p => currentDir.Contains(p.InstalledPath)).Select(p => p).DefaultIfEmpty(
_productSelected).SingleOrDefault();
}
}
似乎不言自明。它建立了一個ProductViewModel
的集合,找到相關的一個,並且在其上調用Load()
。 ProductViewModel.Load()
包含此代碼:
public class ProductViewModel : ObservableObject
{
private readonly IProfileService _profileService;
private readonly ILoggingService _logger;
private ObservableCollection<ProfileViewModel> _profiles;
private ConfigProfile _defaultConfig;
private ProfileViewModel _currentProfile;
public ListCollectionView Profiles { get; set; }
public bool Load(string errorMessage, bool critical)
{
List<ProfileViewModel> profileVms = new List<ProfileViewModel> { _currentProfile };
profileVms.AddRange(
_profileService.GetSavedProfiles(_data.ProductType).Select(
p =>
{
p.FilePath = current.FilePath;
return new ProfileViewModel(p, _defaultConfig, _profileService) { IsChanged = false };
}));
_profiles = new ObservableCollection<ProfileViewModel>(profileVms);
Profiles = new ListCollectionView(_profiles);
Profiles.SortDescriptions.Add(new SortDescription("ProfileTypeValue", ListSortDirection.Ascending));
Profiles.SortDescriptions.Add(new SortDescription("ProfileName", ListSortDirection.Ascending));
Profiles.CurrentChanged += (sender, args) =>
{
((ProfileViewModel)Profiles.CurrentItem).Initialize();
_currentProfile = Profiles.CurrentItem as ProfileViewModel;
};
return true;
}
當我通過這個代碼在Visual Studio調試步驟,一切執行兩者_profiles
和Profiles
被正確地分配給。但是,執行從MainWindowViewModel
構造函數返回時,_profiles
和Profiles
都爲空。
我按F11兩次來到這裏:
可能是什麼回事?我的對象是否超出了範圍?我想也許這與價值vs參考有關,但我找不到任何東西。謝謝!
難道是你顯然使用類字段(例如'_productService'而不是傳遞給構造函數的參數(例如'_productService')嗎?它可能是由調試器觸發的延遲執行,而不是在執行期間執行? –
您需要向我們展示代碼中的聲明 – RBarryYoung
@RBarryYoung這是怎麼回事? – sirdank