這是我最終做的:
在我的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
和我不同的ViewModels:
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代碼,我宣佈命令綁定等,這些基本上做的是在他們的視圖模型以下
MainViewModel.MyStaticProperty = myBoolValue;
感謝您的回覆,其讓我思考!我發佈了我最終做的,不知道它是乾淨的,但它的工作原理... – Louitbol