我有一个UserControl,其中包含两个ContentControls,需要在运行时有不同的UserControl视图与之绑定。 附带的属性解决方案指出 此处 在Silverlight中似乎不能工作。 或者,我做错了什么。 我还发现 这个但它也没有带来任何乐趣。
我将一个ContentControl命名为 "ActiveItem",使其正常工作,但当然,我不能有两个同名的ContentControl。 但是,当然,我不能有两个相同名称的ContentControls。
先谢谢你的帮助。
吉姆
只要在你的主视图模型上公开两个公共属性,每个属性都是你希望显示的视图模型类型的实例。然后,在你的视图中有一个 ContentControl
与相应的名称。如
public class MyMainViewModel
{
private NavigationViewModel navigation;
private MyContentViewModel main;
public MyMainViewModel()
{
// better to inject factories using constructor injection here
this.Navigation = new NavigationViewModel();
this.Main = new MyContentViewModel();
}
public NavigationViewModel Navigation
{
get { return navigation; }
set { navigation= value; NotifyOfPropertyChanged(() => this.Navigation); }
}
public MyContentViewModel Main
{
get { return main; }
set { main= value; NotifyOfPropertyChanged(() => this.Main); }
}
...
}
<ContentControl x:Name="Navigation" />
...
<ContentControl x:Name="Main" />
这是个老问题了,但是为了防止有人遇到同样的问题,我把我的处理方法贴在这里,从头开始,以更彻底的方式。
Caliburn.Micro.Conductor<Screen>.Collection.AllActive
;Caliburn.Micro.Screen
;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中。
还可以阅读 这个问题,也许会对你有更大的帮助。