【问题标题】:Using a ListBox (or other ItemsControl) to host Caliburn presenters使用 ListBox(或其他 ItemsControl)托管 Caliburn 演示者
【发布时间】:2009-11-27 09:21:28
【问题描述】:

如果我有一个 MultiPresenter 并且我使用 ListBox 来显示它所托管的 Presenters,我如何让 Caliburn 发现和绑定项目的视图和视图模型?

例如,如果我有一个看起来像这样的简单视图:

<UserControl x:Class="MyProject.Views.CarView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <ListBox ItemsSource="{Binding Parts}" />
    </Grid>
</UserControl>

绑定到CarViewModel:

public class CarViewModel : MultiPresenter
{
    public BindableCollection<IPartViewModel> Parts { get; }
}

Parts 集合包含实现IPresenter 并具有相应视图的各种对象,例如WheelViewModelWheelView,以及 EngineViewModelEngineView

我希望 Caliburn 使用视图策略为我解析视图。这可能吗?在这种情况下,我需要怎么做才能正确设置演示者的层次结构?

【问题讨论】:

    标签: wpf mvvm itemscontrol caliburn


    【解决方案1】:

    您不必为此更改演示者层次结构。我只建议您考虑使用 MultiPresenter.Presenters 属性来收集子 ViewModel 以及如果您需要强制执行子 ViewModel 生命周期的 MultiPresenter.OpenMultiPresenter.Shutdown 方法。

    对于绑定问题,您应该为 ListBox 项定义模板:

    <ListBox ItemsSource="{Binding Parts}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <ContentControl cal:View.Model="{Binding}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    使用 cal:View.Model 附加属性,框架负责为每个 ViewModel 创建适当的 View,将其绑定到 ViewModel 并将其注入 ContentControl。

    如果您希望框架正确推断视图,还应确保视图和视图模型的命名空间和类命名遵循 Caliburn default convention。否则,您必须编写自定义 IViewStrategy(不过这并不难)。


    编辑:修复了 cal:View.Model 属性中的绑定表达式

    【讨论】:

    • 我认为正确的 ContentControl 如下所示:
    • 你说得对。实际上,点是多余的。很抱歉错误,感谢您指出。
    猜你喜欢
    • 1970-01-01
    • 2010-11-13
    • 2010-11-02
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 2011-03-22
    相关资源
    最近更新 更多