我如何使用ViewModelViewHost在listviewitemtemplate与ReactiveUI和Xamar
本文关键字:ReactiveUI Xamar listviewitemtemplate 何使用 ViewModelViewHost | 更新日期: 2023-09-27 17:49:42
我正在尝试使用ReactiveUI与Xamarin表单,我遇到了一些困难,让视图模型位置工作在一个ListView,有一个ItemTemplate。
我在AppBootstrapper.cs中注册了View和ViewModel,行如下:
Locator.CurrentMutable.Register(() =>
new MonkeyCellView(), typeof(IViewFor<MonkeyCellViewModel>));
我还在XAML中引用了ReactiveUI.XamForms
名称空间,并将ViewModelViewHost
包装在Page
元素中:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinFormsReactiveListView.Views.MonkeyListView"
xmlns:rui="clr-namespace:ReactiveUI.XamForms;assembly=ReactiveUI.XamForms">
<StackLayout>
<Button x:Name="AddMonkey" Text="Add Monkey"/>
<ListView ItemsSource="{Binding Monkeys}" x:Name="MonkeyList">
<ListView.ItemTemplate>
<DataTemplate>
<Page>
<rui:ViewModelViewHost x:Name="vmvh" ViewModel="{Binding .}" />
</Page>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
注意:您必须将ViewModelViewHost包装在Page元素中,因为这是ReactiveUI与Xamarin Forms在此时为ViewModelViewHost支持的唯一元素,按照此文件:
https://github.com/reactiveui/ReactiveUI/blob/master/ReactiveUI.XamForms/XamForms/ActivationForViewFetcher.cs当我运行XamarinFormsReactiveListView。iOS项目我在system_reflection . targetinvocationexception的InnerException中得到以下错误消息:
不知道如何检测ReactiveUI.XamForms.ViewModelViewHost激活/停用时,您可能需要实现IActivationForViewFetcher
原来我有一点错,而应该是引用我自己的类MonkeyCellView : ViewCell, IViewFor<MonkeyCellViewModel>
内的DataTemplate和绑定它的ViewModel与<views:MonkeyCellView ViewModel="{Binding .}"/>
的当前项目:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamarinFormsReactiveListView.Views.MonkeyListView"
xmlns:views="clr-namespace:XamarinFormsReactiveListView.Views;assembly=XamarinFormsReactiveListView">
<StackLayout>
<Button x:Name="AddMonkey" Text="Add Monkey"/>
<ListView ItemsSource="{Binding Monkeys}" x:Name="MonkeyList">
<ListView.ItemTemplate>
<DataTemplate>
<views:MonkeyCellView ViewModel="{Binding .}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>