gpt4 book ai didi

wpf - 使用 ListBox(或其他 ItemsControl)托管 Caliburn 演示者

转载 作者:行者123 更新时间:2023-12-03 03:27:50 24 4
gpt4 key购买 nike

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

例如,如果我有一个如下所示的简单 View :

<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>

绑定(bind)到CarViewModel:

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

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

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

最佳答案

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

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

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

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

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

<小时/>

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

关于wpf - 使用 ListBox(或其他 ItemsControl)托管 Caliburn 演示者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1807630/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com