【发布时间】:2022-04-20 21:10:27
【问题描述】:
我在尝试在 ListViewItem Data 模板中以响应式显示视图时遇到了一些问题。我有一个 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>
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>
在这里我不确定是使用这种机制来显示视图还是使用 ViewModelViewHost ViewModel="{Binding ItemViewModel}"..
我的 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);
});
}
}
目前使用上述用法,它永远不会进入 WhenActivated 函数,如果我删除 ISupportsActivation 功能,它只会崩溃并显示消息 ViewModel 为空。我想知道让这样的东西工作的正确方法是什么?
我尝试使用 ViewModelViewHost 并在 DataTemplate 中设置 ViewModel 属性,而不是在上面,但它甚至没有到达 ItemView.xaml.cs 支持代码。依赖项最初设置如下:
dependencyResolver.Register(() => new ItemView(), typeof(IViewFor<ItemViewModel>));
【问题讨论】:
-
您没有在数据模板停靠面板中设置任何视图模型。如果您想要自动查看分辨率,可以使用 ViewModelViewHost reactiveui.net/docs/handbook/view-location/#viewmodelviewhost。如果您决定使用它或不使用,则需要使用 xaml 绑定是这种情况。
-
感谢 Glen 的回复,我确实使用了 ViewModelViewHost ViewModel={Binding ItemViewModel} 代替它,但它从未解析视图。我相信该视图在我的 App.cs 中正确设置:Locator.CurrentMutable.Register(() => new ItemView(), typeof(IViewFor
));
标签: c# wpf xaml reactive reactiveui