我有一个 MainView.xaml,绑定到 MainViewModel 就可以了。
我想尝试的是将主窗体上的许多控件拆分为用户控件。
现在,我将 UserControls 与 MainView 一起放入 Views 文件夹中,并将它们命名为 LeftSideControlView.xaml 和 RightSideControlView.xaml。相应的ViewModels位于ViewModels文件夹中,称为LeftSideControlViewModel等。
我成功地将用户控件添加到主视图中:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<UserControls:LeftSideControlView cal:Bind.Model="{Binding}" />
<UserControls:RightSideControlView cal:Bind.Model="{Binding}"
Grid.Column="1" />
</Grid>
它们在设计器中正确显示。这是 xaml 中的其中之一:
<UserControl x:Class="TwitterCaliburnWPF.Library.Views.LeftSideControlView"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<StackPanel>
<Label x:Name="Text" FontSize="25" HorizontalAlignment="Center" Margin="5"/>
<TextBox x:Name="TextBox1"
Width="200"
HorizontalAlignment="Center" FontSize="25" Margin="5" />
<Button Width="200" Height="50" Content="Button!" Margin="20" />
</StackPanel>
</Grid>
我使用 Castle.Windsor 在 Caliburn 的 AppBootstrapper 中添加了视图模型及其接口。
public class ApplicationContainer : WindsorContainer
{
public ApplicationContainer()
{
// Register all dependencies here
Register(
Component.For<IWindowManager>().ImplementedBy<WindowManager>().LifeStyle.Is(LifestyleType.Singleton),
Component.For<IEventAggregator>().ImplementedBy<EventAggregator>().LifeStyle.Is(LifestyleType.Singleton),
Component.For<ILeftSideControlViewModel>().ImplementedBy<LeftSideControlViewModel>(),
Component.For<IRightSideControlViewModel>().ImplementedBy<RightSideControlViewModel>()
);
RegisterViewModels();
}
private void RegisterViewModels()
{
Register(AllTypes.FromAssembly(GetType().Assembly)
.Where(x => x.Name.EndsWith("ViewModel"))
.Configure(x => x.LifeStyle.Is(LifestyleType.Transient)));
}
这是 LeftSideControlViewModel 类:
using Screen = Caliburn.Micro.Screen;
namespace TwitterCaliburnWPF.Library.ViewModels
{
public class LeftSideControlViewModel : Screen, ILeftSideControlViewModel
{
private string _text = "Hello from the Left side!";
private string _textBox1 = "Enter Text Here";
public string Text
{
get { return _text; }
}
public string TextBox1
{
get { return _textBox1; }
}
}
}
这是 MainViewModel,我将继续阅读 Caliburn.Micro 文档中的内容,就像在尝试之前一样,MainViewModel 中没有专门告诉它加载这 2 个控件或显示这 2 个控件。
尽管如此,当应用程序启动并运行时,这些值不会从各自的视图模型绑定到用户控件。
namespace TwitterCaliburnWPF.Library.ViewModels
{
public class MainViewModel : Conductor<IScreen>
{
public MainViewModel()
{
ShowLeftControl();
ShowRightControl();
}
private void ShowRightControl()
{
ActivateItem(new RightSideControlViewModel());
}
private void ShowLeftControl()
{
ActivateItem(new LeftSideControlViewModel());
}
public string TextToDisplay
{
get { return "Coming from the ViewModel!"; }
}
}
}