这是我最终做的:
在我的 app.xaml 中;我声明以下资源:
<Application x:Class="MyProject.GUI.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:MyProject.GUI.ViewModels"
StartupUri="MainWindow.xaml">
<Application.Resources>
<vm:MainViewModel x:Key="MainViewModel" />
</Application.Resources>
</Application>
此 MainViewModel 公开一个静态属性,如下所示:
static bool _myStaticProperty;
public static bool MyStaticProperty
{
get
{
return _myStaticProperty;
}
set
{
_myStaticProperty = value;
NotifyStaticPropertyChanged("MyStaticProperty");
}
}
还有如下静态INPC机制:
#region Static property INPC mechanism
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
static void NotifyStaticPropertyChanged(string propertyName)
{
if (StaticPropertyChanged != null)
{
StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
还有我不同的视图模型:
FirstChildViewModel _firstChildViewModel;
public FirstChildViewModel FirstChildViewModel
{
get
{
if (_firstChildViewModel == null)
_firstChildViewModel = new FirstChildViewModel();
return _firstChildViewModel;
}
}
//then a second one, a third one and so on
绑定到我的用户控件如下
<UserControl x:Class="MyProject.GUI.Views.FirstChildControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MyProject.GUI.ViewModels"
mc:Ignorable="d"
DataContext="{Binding Path=FirstChildViewModel,
Source={StaticResource MainViewModel}}">
在我的用户控件的 xaml 代码中,我声明了命令绑定等,它们基本上在他们的 ViewModel 中执行以下操作
MainViewModel.MyStaticProperty = myBoolValue;