'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. I have a ListView in, for example ReceiptView.xaml whose source is bound like such
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
<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}"..
My ItemView.xaml.cs is as such
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. 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. The dependencies are setup initially like:
dependencyResolver.Register(() => new ItemView(), typeof(IViewFor<ItemViewModel>));
Solution 1:[1]
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
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | SolarBear |