简体   繁体   English

无法将ViewModel绑定到View,这是带有ReactiveUI的ListViewItem DataTemplate的一部分

[英]Trouble binding ViewModel to View, as part of a ListViewItem DataTemplate with ReactiveUI

I'm having some issues trying to display a view in a ListViewItem Data template in reactive. 我在尝试在反应式的ListViewItem数据模板中显示视图时遇到一些问题。 I have a ListView in, for example ReceiptView.xaml whose source is bound like such 我有一个ListView,例如ReceiptView.xaml,其源代码绑定成这样

this.WhenActivated(d =>
  {
     this.OneWayBind(ViewModel, vm => vm.Items, view => 
                    view.ReceiptListView.ItemsSource).DisposeWith(d);
  });

where in ReceiptViewModel - Items is an IObservableCollection<ItemsViewModel>

The ItemTemplate for the ListView is as such ListView的ItemTemplate就是这样

<DataTemplate x:Key="ItemTemplate" DataType="{x:Type viewModel:ItemViewModel}">
       <DockPanel
              Width="{Binding Path=ViewportWidth, RelativeSource={RelativeSource AncestorType={x:Type ScrollViewer}}}"
              Margin="0,5"
              HorizontalAlignment="Left"
              Background="Transparent">
              <views:ItemView />
         </DockPanel>
 </DataTemplate>

It is here where I'm unsure whether to use this mechanism for displaying the view or the ViewModelViewHost ViewModel="{Binding ItemViewModel}".. 在这里,我不确定是使用此机制来显示视图还是使用ViewModelViewHost ViewModel =“ {Binding ItemViewModel}”。

My ItemView.xaml.cs is as such 我的ItemView.xaml.cs就是这样

public partial class ItemView : ReactiveUserControl<ItemViewModel>, ISupportsActivation
{
    public ItemView()
    {
        Activator = new ViewModelActivator();

        InitializeComponent();

        this.WhenActivated(d =>
        {
            this.Bind(ViewModel, vm => vm.Name, v => v._Name.Text).DisposeWith(d);
        });
  }
}

Currently with the usage above, it never goes into the WhenActivated function, if I remove the ISupportsActivation functionality, it just crashes out with the message ViewModel is null. 当前具有上述用法,它永远不会进入WhenActivated函数,如果我删除ISupportsActivation功能,它将崩溃,并显示ViewModel为null的消息。 I was wondering what the correct way is to get something like this working? 我想知道使这种工作正常的正确方法是什么?

I have tried using ViewModelViewHost and setting the ViewModel property inside the DataTemplate instead of above but it doesn't even reach the ItemView.xaml.cs backing code. 我尝试使用ViewModelViewHost并在DataTemplate而不是上面的视图中设置ViewModel属性,但是它甚至没有达到ItemView.xaml.cs的支持代码。 The dependencies are setup initially like: 依赖项的初始设置如下:

dependencyResolver.Register(() => new ItemView(), typeof(IViewFor<ItemViewModel>));

The solution, in respect of actually getting it to work, was a matter of binding issue. 关于使其真正起作用的解决方案是一个具有约束力的问题。 I needed to use ViewModelViewHost ViewModel="{Binding .}" within the DataTemplate. 我需要在DataTemplate中使用ViewModelViewHost ViewModel =“ {Binding。}”。

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

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