我正在尝试将ReactiveUI与Xamarin Forms一起使用,并且在使View Model Location在具有ItemTemplate的ListView中工作时遇到了一些困难。
我已经使用以下行在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 for ViewModelViewHost的ReactiveUI支持的唯一元素,根据此文件:
https://github.com/reactiveui/ReactiveUI/blob/master/ReactiveUI.XamForms/XamForms/ActivationForViewFetcher.cs
当我运行 XamarinFormsReactiveListView.iOS 项目时,在System.Reflection.TargetInvocationException的InnerException中收到以下错误消息:
不知道如何检测何时激活/停用ReactiveUI.XamForms.ViewModelViewHost,您可能需要实现IActivationForViewFetcher
最佳答案
原来我有点不对劲,应该在DataTemplate中引用我自己的类MonkeyCellView : ViewCell, IViewFor<MonkeyCellViewModel>
,并使用<views:MonkeyCellView ViewModel="{Binding .}"/>
将其ViewModel绑定到当前项目:
<?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>
关于c# - 如何在具有ReactiveUI和Xamarin表单的ListView ItemTemplate中使用ViewModelViewHost?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30315323/