CM中实现一个比较有意思的特性,就是智能匹配。

通常使用MVVM的写法:在匹配 View和ViewModel时会使用DataContext,在匹配数据属性时使用Binding,在匹配事件命令时使用Command。

而CM通过ElementConvention 实现它们的自动匹配,只需要遵循指定的命名规则[可自定义]。由于一个控件的事件有多种(比如:Button:Click,MouseEnter等等),CM提供了最常用的事件的绑定,可根据具体需求自定义。

自动绑定演示:

在View中添加如下代码:

<Window
    x:Class="Caliburn.Micro.Demo.ShellView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cal="http://www.caliburnproject.org">

    <Grid Background="White">
        <TextBlock x:Name="TbMain" FontSize="50" />
        <Button
            x:Name="OpenOneChild"
            Width="120"
            Height="30"
            Content="OpenOneWindow" />
    </Grid>

</Window>

在ViewModel中添加:

  public class ShellViewModel : Caliburn.Micro.PropertyChangedBase, IShell
    {
        private readonly IWindowManager windowManager;

        [ImportingConstructor]
        public ShellViewModel(IWindowManager windowManager)
        {
            TbMain = "This is ShewView";
            this.windowManager = windowManager;
        }
        private string _tbMain;
        public string TbMain
        {
            get { return _tbMain; }
            set
            {
                _tbMain = value;
                NotifyOfPropertyChange(() => TbMain);
            }
        }

        public void OpenOneChild()
        {
            ChildOneViewModel oneViewModel=new ChildOneViewModel();
            windowManager.ShowDialog(oneViewModel);
        }

项目中新建一个ChildOneView.xaml和一个ChildOneViewModel.cs。

 

<Window
    x:Class="Caliburn.Micro.Demo.ChildOneView"
    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:local="clr-namespace:Caliburn.Micro.Demo"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="ChildOneView"
    Width="300"
    Height="300"
    mc:Ignorable="d">
    <StackPanel>
        <TextBlock x:Name="ChildOne" />
        <TextBox Text="{Binding ChildOne}" />
        <TextBox />
    </StackPanel>
</Window>
View Code

相关文章: