所以我以這種方式設定了我的應用程式。
MyApp.xaml包含我的視圖的 DataTemplates,它們UserControl是
<Application.Resources>
<ResourceDictionary>
<DataTemplate DataType="{x:Type vms:ProtectionViewModel}">
<view:ProtectionView />
</DataTemplate>
<DataTemplate DataType="{x:Type vms:CloudViewModel}">
<view:CloudView />
</DataTemplate>
</ResourceDictionary>
</Application.Resources>
然后我有我的MainWindow.xaml,它由 2 個按鈕和一個ContentPresenter
<RadioButton Content="Y"
FontSize="16"
Foreground="LightGray"
Padding="0,0,0,1"
Command="{Binding ShowProtectionViewCommand}"/>
<RadioButton Content="Z"
FontSize="16"
Foreground="LightGray"
Padding="0,0,0,1"
Command="{Binding ShowCloudViewCommand}"/>
<ContentPresenter Content="{Binding CurrentView}" />
截至目前,當我單擊其中一個按鈕時,它會更改CurrentView為 ViewModel,然后根據 ViewModel 更改 View,如前面所示App.xaml
通過做這個
private object _currentView;
public object CurrentView
{
get { return _currentView; }
set
{
_currentView = value;
OnPropertyChanged();
}
}
public ProtectionViewModel ProtectionViewModel { get; set; } = new ProtectionViewModel();
public CloudViewModel CloudViewModel { get; set; } = new CloudViewModel();
ShowProtectionViewCommand = new RelayCommand(o => { CurrentView = ProtectionViewModel; });
ShowCloudViewCommand = new RelayCommand(o => { CurrentView = CloudViewModel; });
這一切都很完美,我可以切換視圖并保持相同的 DataContext,這很棒。問題是,如果我想要一個可以從多個 ViewModel 訪問的全域屬性,該怎么辦?
看看我
我所有的視圖都有自己的 ViewModel,MainWindowhas MainViewModel,ProtectionViewhasProtectionViewModel等。
uj5u.com熱心網友回復:
我認為不需要答案,但我們在問題下的評論空間已經用完了,所以讓我來說明一下。
這樣做像這樣(你必須假裝我實作了INotifyPropertyChanged)
public class CommonVm : INotifyPropertyChanged
{
// Static instance property
public static CommonVm Instance { get; } = new CommonVm();
// Non static properties against which you can bind.
// Imagine I wrote full implementations with INPC
public int PropertyA { get; set; }
public string PropertyB { get; set; }
}
然后
public class CloudViewModel
{
public CommonVm CommonObject => CommonVm.Instance;
}
然后在 XAML 中假設您的 DataContext 是CloudViewModel
<TextBox Text="{Binding CommonObject.PropertyB}"/>
不管你想說什么,它肯定不是依賴注入
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457171.html
下一篇:從物件串列中的串列中洗掉值
