这是一个老问题,但如果有人遇到同样的问题,我在这里发布我从一开始就以更彻底的方式处理它的方式:
- 包含两个(甚至两个以上)用户控件的主窗口必须继承自
Caliburn.Micro.Conductor<Screen>.Collection.AllActive
;
- 您的用户控件必须继承自
Caliburn.Micro.Screen
;
- 您还必须牢记命名约定。如果在 View 中使用MenuUC作为 ContentControl 的名称,还要在 ViewModel 中创建一个名为MenuUC的属性;
- 像在构造函数中一样初始化您的 UserControl;
- 现在您可以在代码中的任何地方使用
ActivateItem(MenuUC)
和。DeactivateItem(MenuUC)
Caliburn.Micro 会自动检测您要使用哪一个。
示例 XAML 查看代码:
<Window x:Class="YourProject.Views.YourView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="YourViewTitle" Width="900" Height="480">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="4*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Menu Side Bar -->
<ContentControl Grid.Row="0" Grid.Column="0" x:Name="MenuUC" />
<!-- Panel -->
<Border Grid.Column="1" Grid.RowSpan="2" BorderThickness="1,0,0,0" BorderBrush="#FF707070" >
<ContentControl x:Name="PanelUC" />
</Border>
</Grid>
</Window>
示例 C# ViewModel 代码:
class YourViewModel : Conductor<Screen>.Collection.AllActive
{
// Menu Side Bar
private MenuUCViewModel _menuUC;
public MenuUCViewModel MenuUC
{
get { return _menuUC; }
set { _menuUC = value; NotifyOfPropertyChange(() => MenuUC); }
}
// Panel
private Screen _panelUC;
public Screen PanelUC
{
get { return _panelUC; }
set { _panelUC = value; NotifyOfPropertyChange(() => PanelUC); }
}
// Constructor
public YourViewModel()
{
MenuUC = new MenuUCViewModel();
ActivateItem(MenuUC);
PanelUC = new FirstPanelUCViewModel();
ActivateItem(PanelUC);
}
// Some method that changes PanelUC (previously FirstPanelUCViewModel) to SecondPanelUCViewModel
public void ChangePanels()
{
DeactivateItem(PanelUC);
PanelUC = new SecondPanelUCViewModel();
ActivateItem(PanelUC);
}
}
在上面的示例中,ChangePanels()
充当将新用户控件加载到 ContentControl 中的方法。
另请阅读此问题,它可能会对您有所帮助。