![](/img/trans.png)
[英]get value of a property from one viewmodel's current instance in another
[英]Get PropertyChanged notification from one ViewModel to another
我正在做我的第一個 WPF 項目。 我的用戶界面需要更具交互性。 我有 2 個視圖模型。 MainWindowViewModel 和 WorldViewModel。
MainWindow xaml 簡化代碼:
<Window>
[...]
<Window.DataContext>
<vm:MainWindowViewModel />
</Window.DataContext>
<Grid>
<!--Worlds combobox-->
<ComboBox Margin="2 0 0 0" MinWidth="100" IsEnabled="{Binding IsWorldsComboEnabled}"
ItemsSource="{Binding WorldViewModel.Worlds}" SelectedValue="{Binding WorldViewModel.CurrentWorld}"
DisplayMemberPath="Name"/>
</Grid>
</Window>
MainWindowViewModel.cs 代碼:
public class MainWindowViewModel : BaseViewModel
{
public WorldViewModel WorldViewModel { get; set; }
public bool IsWorldsComboEnabled => WorldViewModel.Worlds != null;
/// <summary>
/// Default constructor
/// </summary>
public MainWindowViewModel()
{
WorldViewModel = WorldViewModel.Instance;
}
}
WorldViewModel.cs 代碼:
public class WorldViewModel : BaseViewModel
{
public ObservableCollection<World> Worlds { get; set; }
public World CurrentWorld { get; set; }
public static WorldViewModel Instance { get; set; }
// Called on startup
public static void Initialize()
{
Instance = new WorldViewModel();
}
/// <summary>
/// Default constructor
/// </summary>
public WorldViewModel()
{
}
}
ViewModels 有點大,但這是最少需要的代碼。 BaseViewModel
是一個類,它通過PropertyChanged.Fody
NuGet 包提供 NotifyPropertyChanged 接口。
當Worlds
ObservableCollection 為 null 時,必須禁用我的ComboBox
。 當IsWorldsComboEnabled
位於WorldViewModel
時效果很好,但我覺得這不是一條路。 多個視圖將取決於WorldViewModel
但它們不需要IsWorldsComboEnabled
屬性。 所以它的位置在MainWindowViewModel
。
當WorldViewModel
中的屬性發生變化時,有什么方法可以通知MainWindowViewModel
嗎?
下面這行代碼的問題是,即使WorldViewModel.Worlds
改變, IsWorldsComboEnabled
的 setter 也永遠不會執行,因此你的PropertyChangedEventHandler
不會被調用。
public bool IsWorldsComboEnabled => WorldViewModel.Worlds != null
您可能會更改為public bool IsWorldsComboEnabled { get; set; }
public bool IsWorldsComboEnabled { get; set; }
public bool IsWorldsComboEnabled { get; set; }
和評估下面的表達式
IsWorldsComboEnabled = WorldViewModel.Worlds != null;
每當您更改 WorldViewModel.Worlds 屬性時。
在您的情況下,屬性是ObservableCollection
,您可能會注冊到 CollectionChanged 事件
WorldViewModel.Worlds.CollectionChanged += MyCollectionChangedMethod;
並在那里評估表達式
private void MyCollectionChangedMethod(object sender, NotifyCollectionChangedEventArgs e)
{
IsWorldsComboEnabled = WorldViewModel.Worlds != null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.