【问题标题】:Caliburn Micro design time using naming conventions使用命名约定的 Caliburn Micro 设计时间
【发布时间】:2013-04-27 08:26:07
【问题描述】:

使用 Caliburn Micro 1.5.1 我试图让设计时绑定在 WP8 应用程序中工作。我创建了一个设计时 ViewModel,我在 PhoneApplicationPage 中明确指定:

<phone:PhoneApplicationPage
    d:DataContext="{Binding Source={d:DesignInstance Type=designTime:StartPageDesignTimeViewModel, IsDesignTimeCreatable=True}}"
    micro:Bind.AtDesignTime="True"

该页面实际上不过是 Telerik 的 RadDataBoundListBox:

<Grid x:Name="ContentPanel">
    <telerikPrimitives:RadDataBoundListBox x:Name="Rooms"  ...>

如您所见,我的 ViewModel(和设计时视图模型)有一个名为 Rooms 的公共属性,我使用命名约定方法将其绑定到 ItemsSource 集合。但是,除非我添加 ItemsSource 属性,否则该方法在设计时不起作用

<Grid x:Name="ContentPanel">
    <telerikPrimitives:RadDataBoundListBox x:Name="Rooms" ItemsSource="{Binding Rooms}" ...>

但是,当我使用 ItemsSource 绑定时,我失去了像 SelectedItem 这样的 CM 连接魔法。有没有办法让我的绑定使用命名约定方法在设计时工作,而不用除设计时属性以外的任何东西修改页面?

【问题讨论】:

    标签: c# data-binding caliburn.micro design-time design-time-data


    【解决方案1】:

    好的,我想通了。我一直在寻找的是始终覆盖现有绑定的能力。 CM 比这更具防御性,因此默认情况下它不会替换 ItemsControl 的现有绑定或值。因此,这种行为在 ConventionManager.cs 中定义:

    AddElementConvention<ItemsControl>(ItemsControl.ItemsSourceProperty, "DataContext", "Loaded")
    .ApplyBinding = (viewModelType, path, property, element, convention) => {
        if (!SetBindingWithoutBindingOrValueOverwrite(viewModelType, path, property, element, convention, ItemsControl.ItemsSourceProperty)) {
            return false;
        }
    
        ApplyItemTemplate((ItemsControl)element, property);
    
        return true;
    };
    

    为了强制框架始终替换绑定,我所做的就是在我的 BootStrapper 中将对 SetBindingWithoutBindingOrValueOverwrite 的调用替换为对 SetBinding 的直接调用。所以:

    ConventionManager.AddElementConvention<ItemsControl>(ItemsControl.ItemsSourceProperty, "DataContext", "Loaded")
                 .ApplyBinding = (viewModelType, path, property, element, convention) => {
                                     ConventionManager.SetBinding(viewModelType, path, property, element, convention, ItemsControl.ItemsSourceProperty);
    
                                     ConventionManager.ApplyItemTemplate((ItemsControl) element, property);
                                     return true;
                                 };
    

    (我还必须对我之前为 RadDataBoundListBox 添加的约定进行此编辑)

    我可以看到在某些情况下,有人可能希望以声明方式强制替换现有绑定。也许我会写一个补丁...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-21
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      相关资源
      最近更新 更多