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

时间:2012-01-20 13:39:05

标签: c# wpf xaml binding caliburn.micro

我有一个名为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>

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

但是永远不会调用ReportListItemViewModel上的吸气剂。

那么Binding会出现什么问题?

1 个答案:

答案 0 :(得分:11)

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

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

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

编辑:

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

如果你设置这样的绑定:

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

它将无效,因为您使用Report覆盖路径Notes。要访问Notes中的Report属性,您必须指定如下项目:

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

或者像这样:

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