繁体   English   中英

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

[英]Caliburn.Micro Binding does not seem to resolve in the view model

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

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

包含Report列表的视图模型:

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.." });
    }
}

以及它的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>

价值转换器:

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();
    }
}

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

视图模型:

public class ReportListItemViewModel : Screen
{
    private Report _report;
    public Report Report
    {
        get { return _report; }
        set { _report = value; }
    }
}

视图:

<Grid>
    <TextBlock Text="{Binding Report, Path=Notes}" />
</Grid>

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

但是从不调用ReportListItemViewModel.Report上的getter。

那么绑定出了什么问题呢?

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

<ContentControl cal:View.Model="{Binding ...}"/>

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

编辑:

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

如果你设置这样的绑定:

<TextBlock Text="{Binding Report, Path=Notes}" />

它将无法工作,因为您将使用Notes覆盖路径Report 要在Report访问Notes属性,您必须指定如下项:

<TextBlock Text="{Binding Report.Notes}" />

或者像这样:

<TextBlock Text="{Binding Path=Report.Notes}" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM