Caliburn.Micro Binding似乎在视图模型中没有解决

Per*_*rry 3 c# wpf xaml binding caliburn.micro

我有一个名为的数据传输对象Report.这些报表对象保存在一个名为的不同类中的可观察集合中Controller.我要做的是创建一个视图,从中获取数据Report并在列表中显示.

我遇到的问题是我似乎无法将视图正确绑定到视图模型.我设法通过使用值转换器并返回我需要的viewmodel来绑定它,但即使视图已附加,Bindings似乎也无法解析.

包含Report列表的viewmodel :

public class ReportListViewModel : Screen, IModule
{
    private Controller _controller;
    public Controller Controller
    {
        get { return _controller; }
        set { _controller = value; }
    }

    public ReportListViewModel(Controller controller)
    {
        Controller = controller;
        Controller.Domain.Reports.Add(new Model.Report() { Notes = "Test Data.." });
    }
}
Run Code Online (Sandbox Code Playgroud)

以及它的XAML视图:

<Grid Background="Blue">
    <StackPanel>
        <StackPanel.Resources>
            <local:ReportToListItem x:Key="reportToListItem" />
        </StackPanel.Resources>
        <ListBox Height="100" x:Name="Controller_Domain_Reports">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ContentControl Content="{Binding Converter={StaticResource reportToListItem}}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>
</Grid>
Run Code Online (Sandbox Code Playgroud)

价值转换器:

internal class ReportToListItem : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var vm = IoC.Get<ReportListItemViewModel>();
        vm.Report = (Report)value;
        var view = ViewLocator.GetOrCreateViewType(typeof(ReportListItemView));
        ViewModelBinder.Bind(vm, view, null);
        return view;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是视图模型和视图,它们将负责显示Report对象的数据.

视图模型:

public class ReportListItemViewModel : Screen
{
    private Report _report;
    public Report Report
    {
        get { return _report; }
        set { _report = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)

视图:

<Grid>
    <TextBlock Text="{Binding Report, Path=Notes}" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

现在我知道视图正在附加,因为触发了该OnViewAttached方法ReportListItemViewModel.我知道视图也正在初始化,因为它的构造函数被触发了.

但是ReportListItemViewModel.Report从来没有被称为吸气剂.

那么绑定出了什么问题?

Nuf*_*fin 11

要使用caliburn自动加载视图,您必须绑定到Caliburn的附加属性:

<ContentControl cal:View.Model="{Binding ...}"/>
Run Code Online (Sandbox Code Playgroud)

否则,您不会将相应的视图加载到内容控件中,而是加载视图模型本身.

编辑:

上面的内容似乎是无稽之谈,因为OP说视图已经创建,我想我也发现了实际的问题:

如果你设置这样的绑定:

<TextBlock Text="{Binding Report, Path=Notes}" />
Run Code Online (Sandbox Code Playgroud)

它不会工作,因为要覆盖的路径ReportNotes.要访问该Notes属性Report,您必须指定如下项目:

<TextBlock Text="{Binding Report.Notes}" />
Run Code Online (Sandbox Code Playgroud)

或者像这样:

<TextBlock Text="{Binding Path=Report.Notes}" />
Run Code Online (Sandbox Code Playgroud)